Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Dynamic Programming High frequency Solution Available Practice Mode

Maximum Product Subarray LeetCode Solution

Tags: #Array #Dynamic Programming

Approach Summary

Track both max and min products ending at i (negatives can flip sign). maxProd[i] = max(nums[i], maxPrev×nums[i], minPrev×nums[i]).

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Dynamic Programming Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Dynamic Programming pattern.

Framework: Dynamic Programming • Interview Prep: Tested at FAANG • Explore all Dynamic Programming problems & invariants →

How to Recognize This Pattern

  • Negative × negative = positive — track min alongside max
  • Kadane's variant with two running products

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Dynamic Programming

Frequently Asked Questions

What is the optimal time and space complexity for Maximum Product Subarray?
The optimal solution for Maximum Product Subarray achieves O(n) runtime complexity and requires O(1) auxiliary space. Two linear sweeps (or one combined sweep) of length n require O(n) operations and O(1) auxiliary variables for prefix, suffix, and max product tracking.
How do I identify that Maximum Product Subarray requires the Dynamic Programming pattern?
In technical interviews, look for key problem signals: Negative × negative = positive — track min alongside max; Kadane's variant with two running products. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Dynamic Programming strategy.
What critical edge cases must be handled in Maximum Product Subarray?
Essential edge cases to verify include: Arrays containing zeros (e.g. [2, 3, -2, 4, 0, 7]) which split the problem into independent subarrays; All negative numbers: odd count vs even count; Single negative element (e.g. [-2]) — should return -2; Array with alternating signs and zeros. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Maximum Product Subarray?
Maximum Product Subarray is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Facebook, Microsoft, Bloomberg, Stripe.
Buy me a coffee
Daily Practice
0/0