Maximum Product Subarray (LeetCode 152): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Set
res = max(nums)so single elements, including zeros, are already considered. - Initialize
curMinandcurMaxto 1, the neutral value for multiplication. - For each number
n, if it is zero, reset both trackers to 1 and skip to the next element. - Save
tmp = curMax * nbefore overwritingcurMax, because the newcurMinneeds the old maximum. - Set
curMax = max(n * curMax, n * curMin, n)andcurMin = min(tmp, n * curMin, n). - Update
res = max(res, curMax)and returnresafter the loop.
Step-by-step example
nums = [2,3,-2,4]
res = max(nums) = 4, andcurMin = curMax = 1.- n = 2:
curMax = max(2, 2, 2) = 2,curMin = 2.resstays 4. - n = 3:
curMax = max(6, 6, 3) = 6,curMin = min(6, 6, 3) = 3.res = 6. - n = -2:
tmp = -12.curMax = max(-12, -6, -2) = -2,curMin = min(-12, -6, -2) = -12.resstays 6. - n = 4:
tmp = -8.curMax = max(-8, -48, 4) = 4,curMin = min(-8, -48, 4) = -48.resstays 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 res1class Solution {
2 public int maxProduct(int[] nums) {
3 int res = nums[0];
4 for (int n : nums) res = Math.max(res, n);
5
6 int curMin = 1, curMax = 1;
7
8 for (int n : nums) {
9 if (n == 0) {
10 curMin = 1;
11 curMax = 1;
12 continue;
13 }
14 int tmp = curMax * n;
15 curMax = Math.max(n * curMax, Math.max(n * curMin, n));
16 curMin = Math.min(tmp, Math.min(n * curMin, n));
17 res = Math.max(res, curMax);
18 }
19 return res;
20 }
21}1class Solution {
2public:
3 int maxProduct(vector<int>& nums) {
4 int res = *max_element(nums.begin(), nums.end());
5 int curMin = 1, curMax = 1;
6
7 for (int n : nums) {
8 if (n == 0) {
9 curMin = 1;
10 curMax = 1;
11 continue;
12 }
13 int tmp = curMax * n;
14 curMax = max({n * curMax, n * curMin, n});
15 curMin = min({tmp, n * curMin, n});
16 res = max(res, curMax);
17 }
18 return res;
19 }
20};Time and space complexity
O(n)
One pass computes max(nums) and a second pass does constant work per element, so the total is linear.
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
curMaxfirst and then using the new value to computecurMin. You must save the old maximum intmpbefore 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
resto 0 or 1. If the array is [-3], the answer is -3, soresmust start from an actual element. - Forgetting to include
nitself 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.