Maximum Product Subarray
Maximum Product Subarray is LeetCode 152 (Medium). Given an integer array nums, return the largest product of any non-empty run of neighbouring elements (a contiguous subarray).
- Every value is between −10 and 10, so negative numbers and zeros show up all the time.
- The answer always fits in a 32-bit integer.
The array can hold 20,000 values, so trying every start and end (about 200 million pairs) is too slow. One pass is the target.
- 1 <= nums.length <= 2 * 10⁴
- -10 <= nums[i] <= 10
- The product of any subarray of nums is guaranteed to fit in a 32-bit integer.
Intuition
With sums, the bigger running total is always the one worth extending. With products that rule breaks: multiplying by a negative number turns the smallest product into the largest. So for the subarray ending at each index, keep two numbers:
- Best: the largest product of a subarray that ends here.
- Worst: the smallest (most negative) product of a subarray that ends here. It is kept because one more negative value flips it into a big positive.
A new value x can start a fresh subarray, extend the best one, or extend the worst one. The largest of those three is the new best, the smallest is the new worst, and the answer is the largest best seen at any index.
Carry a maximum and a minimum together whenever one step can reverse the order of values, as multiplying by a negative does. A sum-style scan keeps only the best value, and that is exactly what fails here.
Approach
Before reading on, work out by hand why [-2, 3, -4] has answer 24, and which running product a sum-style scan would have thrown away on the way. Aim for O(n) time and O(1) extra space.
Seed everything with the first value
Set best, worst and ans to nums[0]. The only subarray that ends at index 0 is the first element itself, so it is both the largest and the smallest product so far.
Build three candidates for each new value
For each later value x, compute x, x * best and x * worst. The first starts a new subarray at x; the other two extend the subarray that had the largest or the smallest product one step earlier.
Why three candidates are enough
Any subarray ending at x is either x alone or some subarray ending one step earlier, times x. Multiplying by x keeps the order of values when x is positive and reverses it when x is negative, so the extremes always come from the old best or the old worst.
Keep the largest and the smallest
The new best is the largest of the three candidates and the new worst is the smallest. Both must be computed from the old pair, so build the candidates first and assign both values together.
Update the answer at every index
Set ans = max(ans, best) after each value. The winning subarray can end anywhere in the array, not only at the last element, so checking only at the end would miss it.
Let zeros reset the scan
When x is 0, all three candidates are 0, so best and worst both become 0. At the next value, starting fresh is always one of the candidates, so the scan restarts after the zero with no extra code.
Code in Python, C++ and Java
Common pitfalls
Keeping only the largest product
best = max(x, x * best) ans = max(ans, best)
cands = (x, x * best, x * worst) best, worst = max(cands), min(cands)
On [-2, 3, -4] this returns 3 instead of 24. The product −6 of [-2, 3] is thrown away as useless, but it is the one that −4 turns into 24.
Updating best before computing worst
best = max(x, x * best, x * worst) worst = min(x, x * best, x * worst)
cands = (x, x * best, x * worst) best, worst = max(cands), min(cands)
The second line reads the new best, which already includes x. On [-3, -3, -3] it returns 81, a product no subarray has (the answer is 9): the second value sets best to 9, then worst becomes −3 × 9 = −27, a three-value product passed off as a two-value one.
Starting the products at 1
best = worst = ans = 1 for x in nums:
best = worst = ans = nums[0] for x in nums[1:]:
1 is not the product of any subarray, because a subarray cannot be empty. On [-3] the code returns 1 instead of −3.
Edge cases
[-2, 0, -1]The answer is 0, the zero on its own. At the zero, best becomes 0 and ans records it; neither −2 nor −1 can beat it.
Complexity
best, worst and ans are stored.Maximum Product Subarray FAQ
Is there a way to solve it without tracking the minimum?
Yes. Inside a stretch with no zeros, the best subarray is always a prefix or a suffix of that stretch. With an even number of negatives the whole stretch is positive. With an odd number, you must drop at least one negative, and dropping everything up to the first one or from the last one onward leaves the longest positive run. So scan left to right and right to left with a running product, restart it at 1 after each zero, and take the largest value either scan reaches (counting 0 if the array has a zero).
How do I return the subarray itself, not just its product?
Store a start index next to best and next to worst. When x alone wins, the start is the current index; when a product wins, it takes the start of the value it extended. Each time ans improves, save that start and the current index as the answer's range.
Why does [2, 3, -2, 4] give 6 and not 48?
48 is the product of 2, 3 and 4, but those values are not next to each other: −2 sits between 3 and 4. The subarray must be contiguous, and every run that contains −2 has a negative product, so the best is [2, 3] with 6.