Maximum Product Subarray
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an integer array nums, find the non-empty contiguous subarray with the largest product, and return that product.
Understand the problem
- A contiguous subarray is a run of elements next to each other: in
[2, 3, -2, 4],[3, -2]is one, but[2, 4]isn't (it skips elements). - The product is what you get by multiplying all its elements together.
- Negative numbers matter: two negatives multiply to a positive. And
0makes any product it touches0.
Example 1
Input: nums = [2, 3, -2, 4]
Output: 6[2, 3] gives 6. Including -2 makes the product negative.
Example 2
Input: nums = [-2, 0, -1]
Output: 0[-2, -1] would give 2, but it isn't contiguous (the 0 is between them). The best is [0].
Example 3
Input: nums = [-2, 3, -4]
Output: 24The whole array: -2 × 3 × -4 = 24. The two negatives cancel out.
Constraints
1 <= nums.length <= 2 * 10^4-10 <= nums[i] <= 10- The product of any subarray fits in a 32-bit integer.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk the array keeping both the largest and the smallest product of a subarray ending at the current position, because a negative number can turn the smallest into the largest.
The naive approach (and why it's slow)
Try every subarray: for each start, multiply forward to every end. That's O(n²), around 200 million multiplications for 20,000 elements.
Why tracking only the maximum fails
For the largest sum (Maximum Subarray), you only need "the best sum ending here". Products are different because of negative numbers:
[-2, 3, -4]
ending at -2: products -2
ending at 3: products 3, or -2 × 3 = -6
ending at -4: -6 × -4 = 24 ← the SMALLEST product became the LARGESTIf you had only kept the maximum (3) at the second step, you'd get 3 × -4 = -12 and miss 24.
The key insight: keep the max and the min
At each element x, a subarray ending at x either:
- starts fresh at
x(also how a0"resets" everything), or - extends the subarray ending just before it, multiplying by
x.
The best and worst products ending at x must be among three candidates:
candidates = [x, x × maxHere, x × minHere]
new maxHere = max(candidates)
new minHere = min(candidates)Track the overall best (the largest maxHere seen). Compute both new values from the old pair before overwriting either one.
Step by step
nums = [-2, 3, -4]. Start with everything at the first element, -2:
x | Candidates [x, x × max, x × min] | maxHere | minHere | best |
|---|---|---|---|---|
-2 | (start) | -2 | -2 | -2 |
3 | [3, -6, -6] | 3 | -6 | 3 |
-4 | [-4, -12, 24] | 24 | -12 | 24 |
Answer: 24.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One pass.
- Memory: O(1). Three variables.
Common mistakes
- Tracking only the maximum. Negatives break it, as shown above.
- Updating
maxHereand then using the new value to computeminHere. Compute both from the old values first. - Starting
bestat0. If every number is negative and alone, like[-3], the answer is-3. Start withnums[0].
Going deeper
This is a cousin of Kadane's algorithm from Maximum Subarray (the "best ending here" idea). The extra twist, tracking the minimum because a sign flip can turn the worst into the best, is a useful trick whenever multiplication or negation is involved.
Reference solution
/**
* @param {number[]} nums
* @return {number}
*/
export default function maxProduct(nums) {
// Largest and smallest product of a subarray ENDING at the current element.
// We need the smallest too: a negative number can flip it into the largest.
let maxHere = nums[0]
let minHere = nums[0]
let best = nums[0] // largest product seen anywhere (not 0: everything may be negative)
for (let i = 1; i < nums.length; i++) {
const x = nums[i]
// Start fresh at x, or extend the best / worst subarray ending just before it.
const candidates = [x, x * maxHere, x * minHere]
// Both come from the OLD values, already captured in `candidates`.
maxHere = Math.max(...candidates)
minHere = Math.min(...candidates)
best = Math.max(best, maxHere)
}
return best
}export default function maxProduct(nums: number[]): number {
// Largest and smallest product of a subarray ENDING at the current element.
// We need the smallest too: a negative number can flip it into the largest.
let maxHere = nums[0]
let minHere = nums[0]
let best = nums[0] // largest product seen anywhere (not 0: everything may be negative)
for (let i = 1; i < nums.length; i++) {
const x = nums[i]
// Start fresh at x, or extend the best / worst subarray ending just before it.
const candidates = [x, x * maxHere, x * minHere]
// Both come from the OLD values, already captured in `candidates`.
maxHere = Math.max(...candidates)
minHere = Math.min(...candidates)
best = Math.max(best, maxHere)
}
return best
}def max_product(nums: list[int]) -> int:
# Largest and smallest product of a subarray ENDING at the current element.
# We need the smallest too: a negative number can flip it into the largest.
# best: largest product seen anywhere (not 0: everything may be negative).
max_here = min_here = best = nums[0]
for x in nums[1:]:
# Start fresh at x, or extend the best / worst subarray ending just before it.
candidates = (x, x * max_here, x * min_here)
max_here, min_here = max(candidates), min(candidates)
best = max(best, max_here)
return best