Maximum Product Subarray (LeetCode 152): Solution and Explanation

Medium
Array
Dynamic Programming

Given an integer array that can contain negatives and zeros, find the contiguous non-empty subarray whose elements multiply to the largest value, and return that product.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force tries every start index, extends the subarray one element at a time while multiplying, and keeps the best product. That is O(n²), which is too slow for twenty thousand elements but is a useful mental model: for each position you want the best product of a subarray ending there.

For maximum sum subarray you would only carry the best sum ending at the previous index. Products are different because of negative numbers. A very negative product can become the largest positive one the moment you multiply it by another negative. So the smallest product ending at the previous index is just as valuable as the largest one.

That leads to carrying two values. For each new number n, the best product ending here is the largest of n alone, n times the previous maximum, and n times the previous minimum. The smallest product ending here is the smallest of the same three. A zero wipes out any running product, so the reference code resets both trackers to 1 and moves on; the answer can still be zero because res starts at max(nums).

Approach: Track running max and min products

  1. Set res = max(nums) so single elements, including zeros, are already considered.
  2. Initialize curMin and curMax to 1, the neutral value for multiplication.
  3. For each number n, if it is zero, reset both trackers to 1 and skip to the next element.
  4. Save tmp = curMax * n before overwriting curMax, because the new curMin needs the old maximum.
  5. Set curMax = max(n * curMax, n * curMin, n) and curMin = min(tmp, n * curMin, n).
  6. Update res = max(res, curMax) and return res after the loop.

Step-by-step example

nums = [2,3,-2,4]
  1. res = max(nums) = 4, and curMin = curMax = 1.
  2. n = 2: curMax = max(2, 2, 2) = 2, curMin = 2. res stays 4.
  3. n = 3: curMax = max(6, 6, 3) = 6, curMin = min(6, 6, 3) = 3. res = 6.
  4. n = -2: tmp = -12. curMax = max(-12, -6, -2) = -2, curMin = min(-12, -6, -2) = -12. res stays 6.
  5. n = 4: tmp = -8. curMax = max(-8, -48, 4) = 4, curMin = min(-8, -48, 4) = -48. res stays 6.
  6. Return 6, the product of the subarray [2,3].

Code: Python, Java, C++

1class Solution:
2    def maxProduct(self, nums: List[int]) -> int:
3        res = max(nums)
4        curMin, curMax = 1, 1
5        
6        for n in nums:
7            if n == 0:
8                curMin, curMax = 1, 1
9                continue
10            
11            tmp = curMax * n
12            curMax = max(n * curMax, n * curMin, n)
13            curMin = min(tmp, n * curMin, n)
14            res = max(res, curMax)
15        return res

Time and space complexity

Time

O(n)

One pass computes max(nums) and a second pass does constant work per element, so the total is linear.

Space

O(1)

Only res, curMin, curMax and tmp are stored, no matter how long the array is.

Other approaches

Prefix and suffix products (time O(n), space O(1))

Scan left to right multiplying a running prefix and right to left multiplying a running suffix, resetting each to 1 after a zero, and take the largest value seen. It works because the best subarray always touches one end of a zero-free segment once you drop either the first or the last negative.

Brute force over all subarrays (time O(n²), space O(1))

For every start index, extend to the right while multiplying and record the best product. It is easy to get right and handy for testing, but it is quadratic.

Common mistakes

  • Updating curMax first and then using the new value to compute curMin. You must save the old maximum in tmp before overwriting it.
  • Tracking only the maximum, which fails on inputs like [-2,3,-4] where the answer 24 comes from a negative times a negative.
  • Initializing res to 0 or 1. If the array is [-3], the answer is -3, so res must start from an actual element.
  • Forgetting to include n itself in the max and min, which prevents a new subarray from starting fresh after a bad run.

Frequently asked questions

Why do we need to track the minimum product?

A negative number flips signs. The smallest, most negative product ending at the previous index can turn into the largest product when multiplied by a negative, so you have to keep it around to catch that case.

How are zeros handled in maximum product subarray?

A zero ends every subarray that crosses it, because any product through it is zero. The reference code resets both trackers to 1 so the next element starts fresh, and res begins at max(nums) so an answer of 0 is still captured.

Is this the same as Kadane's algorithm?

It is a close cousin. Kadane carries the best sum ending at each index, while this problem carries both the best and worst product ending at each index because multiplication by a negative swaps them.

Can the product overflow?

The constraints promise that prefix and suffix products fit in a 32-bit integer, so the final answer is safe. Intermediate values such as n * curMin are worth a second look in Java or C++, and using a 64-bit type for the trackers removes any doubt at no real cost. Python integers never overflow.