Best Time to Buy and Sell Stock LeetCode 121 Solution

📌 Day 2/100 – #100DaysOfDSA Continuing the journey 🚀 🔍 Problem Solved: Best Time to Buy and Sell Stock (LeetCode 121) 🧠 What I learned: How to track the minimum price so far while iterating Calculating maximum profit in a single pass Optimizing from brute force O(n²) → O(n) ✅ Solution Approach: Traverse the array once 👣 Update the minimum price Calculate profit at each step and track the maximum 📈 💡 Key Insight: Instead of checking all pairs, track the lowest price before the current day 💻 Code (JavaScript): var maxProfit = function (prices) { let min = prices[0]; let maxProfit = 0; for (let i = 0; i < prices.length; i++) { if (min > prices[i]) { min = prices[i]; } if (prices[i] - min > maxProfit) { maxProfit = prices[i] - min; } } return maxProfit; }; ⚡ Takeaway: A simple observation can drastically reduce complexity — that’s the power of DSA Consistency is the goal — Day 2 done ✅ If you're also solving daily, let’s connect and grow together 🤝 #100DaysOfDSA #DataStructures #Algorithms #LeetCode #Programming #DeveloperJourney #ProblemSolving

To view or add a comment, sign in

Explore content categories