Max Product Subarray on LeetCode with Dynamic Programming

Day 38 of My DSA Journey Today I solved LeetCode 152 – Maximum Product Subarray on LeetCode. 📌 Problem Given an integer array nums, find the contiguous subarray that has the largest product, and return that product. Example: Input: [2,3,-2,4] Output: 6 → subarray [2,3] 🧠 Approach – Dynamic Programming (Tracking Max & Min) This problem is tricky because of negative numbers. Key Idea: • At each index, we maintain: maxProduct → maximum product ending at current index minProduct → minimum product ending at current index 👉 Why min? Because a negative number can turn a small (negative) product into a large positive one. Steps I followed: • Initialize maxProduct, minProduct, and ans with the first element • Traverse the array from left to right • If the current number is negative → swap max and min • Update: maxProduct = max(current, current × maxProduct) minProduct = min(current, current × minProduct) • Update the final answer using maxProduct ⏱ Time Complexity: O(n) — Single pass through the array 📦 Space Complexity: O(1) — No extra space used 💡 Key Learnings ✔ Handling negative numbers in product problems ✔ Using dynamic programming with state tracking ✔ Understanding why tracking both max & min is important This is one of those problems that looks simple but tests deep understanding of edge cases 🚀 Consistency continues — leveling up every day 💪 #100DaysOfCode #DSA #DynamicProgramming #Arrays #LeetCode #Java #ProblemSolving #CodingJourney #DeveloperJourney #Programming #SoftwareEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories