Maximum Product Subarray
Difficulty: Medium
Given an integer array nums (which may include negatives and zeros), return the largest product of any contiguous subarray.
Examples
Input: nums = [2, 3, -2, 4]
Output: 6
The subarray [2, 3] has product 6, which beats any subarray that includes the -2.
Input: nums = [-2, 0, -1]
Output: 0
Any subarray touching the 0 gives a product of 0, and no other subarray beats that (the lone -2 or -1 are both negative).
Input: nums = [-2, 3, -4]
Output: 24
The whole array multiplies to (-2) * 3 * (-4) = 24 — the two negatives cancel out.
Constraints
1 <= nums.length <= 2 * 10^4
-10 <= nums[i] <= 10
Approach
For a maximum sum subarray, you only track the best sum ending at each position. Products break this: multiplying by a negative flips the sign, so the smallest (most negative) product can become the largest after another negative.
So track two values at each position: the maximum and the minimum product ending there. For the next number, the new maximum is the best of:
- Starting fresh with just this number.
- Extending the previous max.
- Extending the previous min (in case this number is negative and flips it).
Do the same for the new minimum, and keep the largest maximum seen at any position as the answer.
Solutions
Brute Force — Check Every Subarray
Compute the product of every contiguous subarray and keep the largest.
function maxProduct(nums) {
let best = nums[0];
for (let i = 0; i < nums.length; i++) {
let product = 1;
for (let j = i; j < nums.length; j++) {
product *= nums[j];
if (product > best) best = product;
}
}
return best;
}Time: O(n^2) · Space: O(1)
Optimal — Track Running Max and Min
Sweep once, carrying both the max and min product ending at each position, since a negative number can turn the min into the new max.
function maxProduct(nums) {
let maxEndingHere = nums[0];
let minEndingHere = nums[0];
let best = nums[0];
for (let i = 1; i < nums.length; i++) {
const num = nums[i];
if (num < 0) {
// A negative number swaps the roles of the running max and min.
[maxEndingHere, minEndingHere] = [minEndingHere, maxEndingHere];
}
maxEndingHere = Math.max(num, maxEndingHere * num);
minEndingHere = Math.min(num, minEndingHere * num);
best = Math.max(best, maxEndingHere);
}
return best;
}Time: O(n) · Space: O(1)