Día 29 DSA: Solución de Problemas

Guía de problemas DSA en JavaScript: suma de elementos de un arreglo y máximo beneficio con una sola compra y venta, con soluciones eficientes y ejemplos prácticos.

17 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Pregunta 1 Suma de elementos

Enunciado Dado un arreglo de enteros llamado prices devuelve la suma de todos los elementos del arreglo

Ejemplo Input [1, 2, 3] Output 6

Enfoque Inicializa una variable sum en 0. Recorre cada elemento del arreglo y suma el valor actual a sum. Al finalizar devuelve sum.

Implementacion ejemplo en JavaScript var SumOfDigits = function(prices) { let sum = 0; for (let i = 0; i < prices.length; i++) { sum += prices[i]; } return sum; }; console.log(SumOfDigits([1,2,3])); // Output 6

Casos borde arreglo vacio [] devuelve 0; arreglo con un elemento [10] devuelve 10; arreglo con numeros negativos [-1, -2, 3] la suma total seria 0 en este ejemplo si se espera ese resultado segun reglas del problema

Complejidad Tiempo O(n) donde n es la longitud del arreglo. Espacio O(1) uso de una variable adicional constante.

Pregunta 2 Maximo beneficio con una sola compra y venta

Enunciado Dado un arreglo prices encuentra el maximo beneficio posible realizando una sola compra y una sola venta con la condicion de comprar antes de vender

Ejemplo Input [7, 1, 5, 3, 6, 4] Output 5

Enfoque Mantener la minima precio vista hasta el momento y el maximo beneficio hasta ahora. Para cada precio calcular el beneficio actual prices[i] minus min_Price actualizar max_Profit si es mayor y actualizar min_Price si el precio actual es menor. Al final devolver max_Profit.

Implementacion ejemplo en JavaScript var maxProfit = function(prices) { if (prices.length === 0) return 0; let min_Price = prices[0]; let max_Profit = 0; for (let i = 1; i < prices.length; i++) { if (prices[i] - min_Price > max_Profit) { max_Profit = prices[i] - min_Price; } if (prices[i] < min_Price) { min_Price = prices[i]; } } return max_Profit; }; console.log(maxProfit([7,1,5,3,6,4])); // Output 5

Complejidad Tiempo O(n) recorremos el arreglo una vez. Espacio O(1) solo variables auxiliares min_Price y max_Profit.

Sobre Q2BSTUDIO Somos Q2BSTUDIO empresa de desarrollo de software y aplicaciones a medida especializada en inteligencia artificial ciberseguridad y soluciones cloud. Desarrollamos software a medida y aplicaciones a medida adaptadas a las necesidades de cada cliente ofreciendo servicios cloud aws y azure servicios inteligencia de negocio e implementacion de power bi. Somos especialistas en inteligencia artificial y ofrecemos soluciones de ia para empresas incluyendo agentes IA personalizados que automatizan procesos y mejoran la eficiencia.

Servicios que ofrecemos Desarrollo de aplicaciones a medida software a medida integracion con servicios cloud aws y azure soluciones de inteligencia artificial implementacion de agentes IA servicios de inteligencia de negocio analitica avanzada y visualizacion con power bi y estrategias de ciberseguridad para proteger datos e infraestructuras.

Por que elegirnos Nuestro equipo combina experiencia en desarrollo a medida con capacidades avanzadas en inteligencia artificial y ciberseguridad para entregar soluciones seguras escalables y orientadas al negocio. Implementamos servicios inteligencia de negocio que transforman datos en decisiones y ofrecemos soporte para despliegues en servicios cloud aws y azure.

Palabras clave aplicaciones a medida software a medida inteligencia artificial ciberseguridad servicios cloud aws y azure servicios inteligencia de negocio ia para empresas agentes IA power bi

Day 29 Of Dsa Problem Solving Este articulo forma parte de la serie Day 29 Of Dsa Problem Solving practica enfocada en resolver problemas clasicos de algoritmos y estructuras de datos aplicando soluciones que pueden integrarse en proyectos reales de Q2BSTUDIO

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