Día 33: Máximos unos consecutivos y más

Soluciones eficientes a problemas clásicos de DSA: Max Consecutive Ones, Consecutive Characters y LCIS con una pasada y O(1) espacio. Descubre cómo Q2BSTUDIO impulsa software a medida, IA y ciberseguridad.

19 ago 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Día 33 de DSA Problem Solving – Max Consecutive Ones y más

Introducción: En esta entrega repasamos tres problemas clásicos de algoritmos que aparecen frecuentemente en entrevistas y competencias: Max Consecutive Ones, Consecutive Characters y Longest Continuous Increasing Subsequence. Además mostramos enfoques, complejidad y ejemplos. Al final encontrarás información sobre Q2BSTUDIO y cómo nuestros servicios en aplicaciones a medida, software a medida, inteligencia artificial y ciberseguridad pueden ayudarte a llevar tus proyectos al siguiente nivel.

Problema 1: Max Consecutive Ones

Descripción: Dado un arreglo binario nums devuelve el número máximo de 1 consecutivos en el arreglo.

Enfoque: Recorremos el arreglo manteniendo un contador actual de unos consecutivos. Si encontramos un 1 incrementamos el contador y actualizamos el máximo. Si encontramos un 0 reiniciamos el contador a 0.

Complejidad temporal: O(n) — recorremos el arreglo una sola vez.

Complejidad espacial: O(1) — espacio auxiliar constante.

Ejemplo: Entrada: [1,1,0,1,1,1] Salida: 3 Explicación: la mayor secuencia de 1 consecutivos tiene longitud 3.

Implementación (JavaScript): function findMaxConsecutiveOnes(nums) { let currentCount = 0; let maxCount = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] === 1) { currentCount++; if (currentCount > maxCount) { maxCount = currentCount; } } else { currentCount = 0; } } return maxCount; }

Problema 2: Consecutive Characters

Descripción: Dada una cadena s devuelve la potencia de la cadena. La potencia es la longitud máxima de una subcadena que contiene un único carácter repetido.

Enfoque: Recorremos la cadena comparando el carácter actual con el anterior. Si son iguales incrementamos el contador actual, si cambian reiniciamos el contador a 1. Llevamos un registro del máximo durante la iteración.

Complejidad temporal: O(n) — una sola pasada por la cadena.

Complejidad espacial: O(1) — sin estructuras adicionales significativas.

Ejemplo: Entrada: abbcccddddeeeeedcba Salida: 5 Explicación: la subcadena más larga con un solo carácter es eeeee con longitud 5.

Implementación (JavaScript): function maxPower(s) { if (s.length === 0) return 0; let currentCount = 1; let maxCount = 1; for (let i = 1; i < s.length; i++) { if (s[i] === s[i - 1]) { currentCount++; } else { currentCount = 1; } if (currentCount > maxCount) maxCount = currentCount; } return maxCount; }

Problema 3: Longest Continuous Increasing Subsequence LCIS

Descripción: Dado un arreglo de enteros nums devuelve la longitud de la subsecuencia estrictamente creciente más larga que sea continua.

Enfoque: Recorremos el arreglo comparando cada elemento con el anterior. Si el elemento actual es mayor incrementamos la longitud actual, si no reiniciamos la longitud a 1. Registramos la máxima longitud encontrada.

Complejidad temporal: O(n) — una sola pasada por el arreglo.

Complejidad espacial: O(1) — solo variables escalares adicionales.

Ejemplo: Entrada: [1,3,5,4,7] Salida: 3 Explicación: la LCIS es [1,3,5] con longitud 3.

Implementación (JavaScript): function findLengthOfLCIS(nums) { if (nums.length === 0) return 0; let maxLen = 1; let currentLen = 1; for (let i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { currentLen++; } else { if (currentLen > maxLen) maxLen = currentLen; currentLen = 1; } } return Math.max(maxLen, currentLen); }

Consejos prácticos: Para estos tres problemas el patrón es el mismo: recorrido lineal manteniendo contadores y actualizando un máximo cuando corresponda. Evitar estructuras pesadas y pensar en estados locales actuales facilita llegar a soluciones O(n) con O(1) de espacio.

Sobre Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones tecnológicas para empresas. Ofrecemos software a medida, aplicaciones a medida y consultoría en inteligencia artificial e ia para empresas. Nuestro equipo diseña agentes IA, integra Power BI para reporting avanzado y desarrolla arquitecturas seguras con servicios cloud aws y azure. Además proporcionamos servicios de inteligencia de negocio y ciberseguridad para proteger tus datos y optimizar la toma de decisiones.

Por qué elegirnos: En Q2BSTUDIO combinamos experiencia en desarrollo con especialización en inteligencia artificial, ciberseguridad y servicios cloud aws y azure. Diseñamos software a medida y aplicaciones a medida adaptadas a procesos reales, construimos agentes IA que automatizan tareas y ofrecemos soluciones de inteligencia de negocio con power bi para transformar datos en resultados accionables. Nuestro enfoque integral incluye evaluación de riesgos y estrategias de ciberseguridad para garantizar continuidad y cumplimiento.

Servicios destacados: desarrollo de aplicaciones a medida, software a medida, implementación de modelos de inteligencia artificial, consultoría en ia para empresas, creación de agentes IA, integración de power bi, servicios cloud aws y azure, soluciones de servicios inteligencia de negocio y auditorías de ciberseguridad.

Contacto y próximos pasos: Si quieres optimizar procesos con inteligencia artificial o desarrollar software a medida seguro y escalable ponte en contacto con Q2BSTUDIO. Podemos ayudarte desde la definición del proyecto hasta la puesta en producción en entornos cloud aws y azure con buenas prácticas de ciberseguridad y dashboards en power bi para decisiones basadas en datos.

Cierre: Sigue practicando problemas de DSA como estos para mejorar habilidades técnicas y de resolución. Mientras tanto, Q2BSTUDIO está lista para convertir ideas en soluciones reales mediante software a medida, aplicaciones a medida y tecnologías avanzadas en inteligencia artificial y ciberseguridad.

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.