Maximum Product Subarray
A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 26 roles
The problem
Given an integer array, find the contiguous subarray that has the largest product of its elements.
Example 1
- Input
- nums = [3,-1,4,2]
- Output
- 8
- Why
- The run [4,2] gives 4 * 2 = 8; any run that includes the -1 without a second negative turns negative.
Example 2
- Input
- nums = [-3,0,-2]
- Output
- 0
- Why
- Each negative on its own is below 0, and the 0 splits them apart, so the best product is the 0 alone.
Example 3
- Input
- nums = [-2,3,-4]
- Output
- 24
- Why
- The product of the entire array is (-2) * 3 * (-4) = 24 due to the double negative.
Constraints
- 1 <= nums.length <= 2*10^4
- -10 <= nums[i] <= 10
How to think about it
Updated 2026-09-29Multiplication by a negative number flips signs: a tiny negative product suddenly becomes a huge positive product when struck by another negative. Because an extreme negative is only one step away from becoming the maximum, tracking both the running maximum and the running minimum at every step is necessary to capture sign flips.
Approaches, worst first
Exhaustive subarray product
time O(n^2) · space O(1)
Evaluate every contiguous range (i, j) by multiplying elements in nested loops and recording the highest product seen. Solves the task directly, but runs in quadratic time and risks numerical overflow on larger subarrays.
Dual max-min dynamic trackingWrite this one
time O(n) · space O(1)
Maintain currentMax and currentMin seeded with nums[0]. For each subsequent number, if negative, swap the two accumulators. Then update both by taking max and min between the number itself and its product with the previous bounds. Updates the global answer in one pass.
Where people lose marks · 3
- Updating currentMax and then using that newly updated value to compute currentMin in the same iteration without preserving the old max.
- Overlooking the reset effect of 0, which zeroes out the running product and forces subsequent subarrays to start fresh from the next element.
- Initializing max product to 0 or 1 instead of nums[0], which fails when the array contains only a single negative number like [-2].
Full solution
Dual max-min dynamic tracking: keep the running maximum AND minimum product ending at each index, swapping them when the current number is negative. One pass, constant space, and it is the only linear approach that survives sign flips and zeros.
Python
from typing import List
def max_product(nums: List[int]) -> int:
best = cur_max = cur_min = nums[0]
for x in nums[1:]:
if x < 0:
cur_max, cur_min = cur_min, cur_max # a negative flips which extreme is which
cur_max = max(x, cur_max * x)
cur_min = min(x, cur_min * x)
best = max(best, cur_max)
return best
JavaScript
function maxProduct(nums) {
let best = nums[0];
let curMax = nums[0];
let curMin = nums[0];
for (let i = 1; i < nums.length; i++) {
const x = nums[i];
if (x < 0) [curMax, curMin] = [curMin, curMax]; // a negative flips which extreme is which
curMax = Math.max(x, curMax * x);
curMin = Math.min(x, curMin * x);
best = Math.max(best, curMax);
}
return best;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
More Arrays problems
Target Roles
Core requirement for 26 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .