LeetCode hasta entrar al Top 1% — Día 61

Solución greedy para Maximum 69 Number (LeetCode): cambia la primera cifra 6 por 9 para obtener el máximo con un solo dígito; complejidad O(n) y ejemplo en Python.

19 ago 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Problema 1323 Maximum 69 Number · Dificultad Easy · Etiquetas Greedy, Math

Resumen del problema · Se recibe un entero positivo compuesto solamente por los dígitos 6 y 9. Se permite cambiar como máximo un dígito y el objetivo es maximizar el número resultante. El cambio puede ser de 6 a 9 o de 9 a 6.

Idea general y razonamiento · Fuerza bruta: reemplazar cada 6 por 9 una por una, calcular todos los números posibles y tomar el máximo. Funciona pero es ineficiente. Estrategia optimizada y greedy: para maximizar basta con cambiar la primera aparición de 6 por 9 desde la izquierda, porque los dígitos más a la izquierda tienen mayor peso en la representación decimal. No hace falta revisar más posiciones, con una sola sustitución se alcanza el máximo posible.

Algoritmo utilizado · Greedy y manipulación de cadenas.

Implementación en Python · Ejemplo compacto de la solución class Solution: def maximum69Number(self, num: int) -> int: num = str(num); num = num.replace(chr(54), chr(57), 1); return int(num)

Complejidad temporal y espacial · Tiempo O(n) donde n es el número de dígitos, por el recorrido y la sustitución de la cadena. Espacio O(n) por la conversión a cadena.

Conclusiones clave · El enfoque greedy funciona porque solo necesitamos maximizar en la posición de mayor peso. · La manipulación de cadenas simplifica problemas basados en dígitos. · En problemas similares es habitual considerar primero el dígito más significativo.

Autochequeo · [x] Pude resolverlo sin ayuda · [x] Escribí el código desde cero · [x] Entendí por qué funciona · [x] Podré recordarlo en una semana

Registro de progreso · Día 61 · Problemas resueltos 417 · Confianza hoy media · LeetCode Rating 1572

Sobre Q2BSTUDIO · Q2BSTUDIO es una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones de software a medida, inteligencia artificial, ciberseguridad y servicios cloud aws y azure. Ofrecemos servicios de inteligencia de negocio, implementación de power bi, agentes IA y soluciones de ia para empresas, todo orientado a mejorar procesos y generar valor. Nuestro equipo desarrolla aplicaciones a medida integrando inteligencia artificial y prácticas de ciberseguridad desde el diseño, y ofrecemos servicios gestionados en plataformas cloud aws y azure para garantizar escalabilidad y seguridad. Si buscas software a medida, aplicaciones a medida, inteligencia artificial o servicios de inteligencia de negocio, Q2BSTUDIO combina experiencia técnica y enfoque consultivo para entregar soluciones end to end.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat