Maximum Product Subarray
Medium · Dynamic programming
Jump to codeFind the largest product of any nonempty contiguous subarray of a nonempty integer array. Values may be positive, negative, or zero.
Examples
Example 1
nums = [2,3,-2,4]
Output: 6
Example 2
nums = [-2,0,-1]
Output: 0
Constraints
- 1 <= nums.length <= 1000
- -10 <= nums[i] <= 10
- The result fits a signed 32-bit integer.
Need a hint?
A very negative product becomes useful when multiplied by another negative value.
Asked in real interviews
Candidates reported versions of Maximum Product Subarray from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Track both the minimum and maximum product ending at the previous index. At value x, the new extremes come from x, x × oldMinimum, and x × oldMaximum. Compute both from the old states, then update the global maximum. Starting anew at x handles zeros and resets.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def maxProduct(nums):
smallest = largest = best = nums[0]
for value in nums[1:]:
candidates = (value, value * smallest, value * largest)
smallest, largest = min(candidates), max(candidates)
best = max(best, largest)
return best
JavaScript solution
function maxProduct(nums) {
let smallest = nums[0], largest = nums[0], best = nums[0];
for (let i = 1; i < nums.length; i++) {
const value = nums[i], a = value * smallest, b = value * largest;
smallest = Math.min(value, a, b);
largest = Math.max(value, a, b);
best = Math.max(best, largest);
}
return best;
}
Java solution
import java.util.*;
class Solution {
public int maxProduct(int[] nums) {
int smallest = nums[0], largest = nums[0], best = nums[0];
for (int i = 1; i < nums.length; i++) {
int value = nums[i], a = value * smallest, b = value * largest;
smallest = Math.min(value, Math.min(a, b));
largest = Math.max(value, Math.max(a, b));
best = Math.max(best, largest);
}
return best;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProduct(vector<int> &nums) {
int smallest = nums[0], largest = nums[0], best = nums[0];
for (size_t i = 1; i < nums.size(); i++) {
int value = nums[i], a = value * smallest, b = value * largest;
smallest = min({value, a, b});
largest = max({value, a, b});
best = max(best, largest);
}
return best;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
2,
3,
-2,
4
]
]6
[
[
-2,
0,
-1
]
]0
[
[
0,
2
]
]2
[
[
-2,
-3,
7
]
]42
[
[
-2,
-3,
-4
]
]12
Drafts are saved per language in this browser when storage is available.