LeetCode #152 Medium

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.

Constraints
  • 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.
dparraykadane
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

6

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxProduct(self, nums):
▶3 best = worst = ans = nums[0]
▶4 for x in nums[1:]:
▶5 cands = (x, x * best, x * worst)
▶6 best, worst = max(cands), min(cands)
▶7 ans = max(ans, best)
▶8 return ans
numsbestworst2223−24answer2candidates for the current valuestart newextend bestextend worstfirst value 2 → best and worst are both 2
best2largest product ending here
worst2smallest product ending here
ans2
Only one subarray ends at index 0: the value 2 itself. So it is both the largest and the smallest product so far, and the answer starts there.
numsbestworst2223−24answer2candidates for the current value3start new6extend best6extend worst3 is positive → order stays
x3index 1
candidates3, 6, 6x, x × best, x × worst
Best and worst are both 2 here, so extending either gives 6. The real choice is between that and starting fresh at 3.
numsbestworst222363−24answer6candidates for the current value3→ worststart new6→ bestextend best6extend worstbest 6 beats the answer → answer 6
best6extended
worst3
ans6
The largest candidate, 6, becomes the best product ending at index 1, and the smallest, 3, becomes the worst. It is bigger than the answer so far, so the answer moves up to 6.
numsbestworst222363−24answer6candidates for the current value−2start new−12extend best−6extend worst−2 is negative → worst can become best
x−2index 2
candidates−2, −12, −6x, x × best, x × worst
Multiplying by a negative −2 reverses the order: the old worst, 3, now gives the larger product (−6) and the old best gives the smaller one (−12). That is why the worst was kept.
numsbestworst222363−2−2−124answer6candidates for the current value−2→ beststart new−12→ worstextend best−6extend worstbest −2 → answer stays 6
best−2start new
worst−12
ans6
The largest candidate, −2, becomes the best product ending at index 2, and the smallest, −12, becomes the worst. It does not beat the answer 6, which comes from an earlier subarray.
numsbestworst222363−2−2−124answer6candidates for the current value4start new−8extend best−48extend worst4 is positive → order stays
x4index 3
candidates4, −8, −48x, x × best, x × worst
Multiplying by a positive 4 keeps the order: the old best, −2, still gives the larger product (−8).
numsbestworst222363−2−2−1244−48answer6candidates for the current value4→ beststart new−8extend best−48→ worstextend worstbest 4 → answer stays 6
best4start new
worst−48
ans6
The largest candidate, 4, becomes the best product ending at index 3, and the smallest, −48, becomes the worst. It does not beat the answer 6, which comes from an earlier subarray.
numsbestworst222363−2−2−1244−48answer6candidates for the current valuestart newextend bestextend worstanswer: 6
return6
The largest best value at any index is 6. The green tiles show the subarray that produces it, ending at index 1.
05

Common pitfalls

Keeping only the largest product

✗ Wrong
best = max(x, x * best)
ans = max(ans, best)
✓ Right
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

✗ Wrong
best = max(x, x * best, x * worst)
worst = min(x, x * best, x * worst)
✓ Right
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

✗ Wrong
best = worst = ans = 1
for x in nums:
✓ Right
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.

06

Edge cases

Every non-zero subarray is negative, as in [-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.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the array, with three multiplications and two comparisons per value. Only best, worst and ans are stored.
08

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.