Find the largest product obtainable from one nonempty contiguous range of an integer list.
Problem
Input. A nonempty integer list nums, possibly containing negative numbers and zeros.
Output. Return the largest product of all values in any nonempty contiguous subarray.
Rules. Select at least one value and do not skip positions inside the selected range. Return the product, not the range or a selection of unrelated values. Leave the list unchanged. Empty input is outside the reference contract.
Example. [2, 3, -2, 4] returns 6 from [2, 3].
For [-2, 0, -1], return 0, not 2, because the two negative values are separated by zero.
Picture
At a completed position, current_max and current_min summarize all nonempty ranges ending there. best saves the largest product seen anywhere.
The swap frames prepare the sources for a negative multiplier. They are intermediate states, not completed endpoint summaries.
Problem trace
Separate full input: update both ending-product extremes from their old values
- scan
- 0
- processed prefix
- [0..0]
- ending range
- [2]
- scan
- 0→1
- processed prefix
- [0..0]→[0..1]
- ending range
- [2]→max [2,3]; min [3]
- scan
- 1→2
- processed prefix
- [0..1]→[0..2]
- action
- not shown→swap current_max=6 and current_min=3
- ending range
- not shown→max [-2]; min [2,3,-2]
- arithmetic
- not shown→max(-2,-6)=-2; min(-2,-12)=-12; best=6
- action
- swap current_max=6 and current_min=3→not shown
- scan
- 2→3
- processed prefix
- [0..2]→[0..3]
- ending range
- max [-2]; min [2,3,-2]→max [4]; min [2,3,-2,4]
- scan
- 3→4
- processed prefix
- [0..3]→[0..4]
- action
- not shown→swap current_max=4 and current_min=-48
- ending range
- not shown→max [2,3,-2,4,-1]; min [4,-1]
- arithmetic
- not shown→max(-1,48)=48; min(-1,-4)=-4; best=48
- result
- not shown→48 from [2,3,-2,4,-1]
- Recognize it
- Use paired extremes for contiguous products when negative values can reverse ordering and zero or a single value may force a restart.
- Keep true
- After each index, current_max and current_min are respectively the largest and smallest products of nonempty subarrays ending exactly there, and best is the largest current_max seen in the processed prefix.
- Reuse it
- When a transition is not monotone, retain every extreme that can become optimal after the next operation; sign-changing multiplication is the canonical max/min pair example.
Reference drawing
Problem trace
A very negative product can become the next positive maximum
Execution trace
- scan
- 0
- processed prefix
- [0..0]
- ending range
- [2]
- scan
- 0→1
- processed prefix
- [0..0]→[0..1]
- ending range
- [2]→max [2,3]; min [3]
- scan
- 1→2
- processed prefix
- [0..1]→[0..2]
- action
- not shown→swap current_max=6 and current_min=3
- ending range
- not shown→max [-2]; min [2,3,-2]
- arithmetic
- not shown→max(-2,-6)=-2; min(-2,-12)=-12; best=6
- action
- swap current_max=6 and current_min=3→not shown
- scan
- 2→3
- processed prefix
- [0..2]→[0..3]
- ending range
- max [-2]; min [2,3,-2]→max [4]; min [2,3,-2,4]
- scan
- 3→4
- processed prefix
- [0..3]→[0..4]
- action
- not shown→swap current_max=4 and current_min=-48
- ending range
- not shown→max [2,3,-2,4,-1]; min [4,-1]
- arithmetic
- not shown→max(-1,48)=48; min(-1,-4)=-4; best=48
- result
- not shown→48 from [2,3,-2,4,-1]
- Recognize it
- Use paired extremes for contiguous products when negative values can reverse ordering and zero or a single value may force a restart.
- Keep true
- After each index, current_max and current_min are respectively the largest and smallest products of nonempty subarrays ending exactly there, and best is the largest current_max seen in the processed prefix.
- Reuse it
- When a transition is not monotone, retain every extreme that can become optimal after the next operation; sign-changing multiplication is the canonical max/min pair example.
Code
Every ending range either starts at num or extends a range ending immediately before it.
A positive multiplier preserves product order. A negative multiplier reverses it, so the old minimum feeds the new maximum and vice versa.
The singleton candidate permits restarting, including after zero. Multiplication by zero collapses both current extremes to zero without deleting the saved global best.
def max_product_subarray(nums: list[int]) -> int:
current_max = current_min = best = nums[0]
for num in nums[1:]:
if num < 0:
current_max, current_min = current_min, current_max
current_max = max(num, current_max * num)
current_min = min(num, current_min * num)
best = max(best, current_max)
return best
Follow the Old Sources
After [2,3], the maximum is six and the minimum is three. Multiplying by -2 gives ending extremes -2 and -12.
At 4, the maximum restarts at four. The minimum extends the whole prefix to -48.
The final -1 turns that minimum into 48. Tracking only the prior maximum would lose this winning range.
Both updates must use the correct old source. The swap formulation does this without recomputing the new minimum from the newly updated maximum.
Boundaries and Cost
Initialize from nums[0], not zero or one. For [-2], the nonempty answer is -2. Empty input raises IndexError.
The reference performs arithmetic operations and leaves the input unchanged. Its literal nums[1:] slice uses auxiliary references.
The recurrence needs three integer slots, but their products may grow. Constant slots do not imply constant bit storage or constant-time multiplication.
Recall: Why did addition need only the maximum? Addition preserves order; multiplication can reverse it, so both extremes may become useful.
Return the Product’s Range
Choose this when: The answer must identify a contiguous witness.
Carry a start index with each ending extreme. Construct all three candidates before replacing either old state.
def maximum_product_range(nums):
high = low = (nums[0], 0)
best = [nums[0], 0, 1]
for index in range(1, len(nums)):
value = nums[index]
candidates = [
(value, index),
(high[0] * value, high[1]),
(low[0] * value, low[1]),
]
high = max(candidates, key=lambda item: item[0])
low = min(candidates, key=lambda item: item[0])
if high[0] > best[0]:
best = [high[0], high[1], index + 1]
return best
For [-2,3,-4], the result is [24,0,3]: product 24 over nums[0:3].
Candidate ties prefer the singleton, then the old maximum, then the old minimum. The global range changes only on strict improvement.
This returns one optimum, not an earliest-start guarantee. Empty input raises IndexError.
Optimize the Minimum Instead
Choose this when: The requested answer is the smallest nonempty product.
Keep both ending extremes, but reduce the minimum into the saved global answer. The objective changes; the sign-dependent transition does not.
def minimum_product_subarray(nums):
high = low = best = nums[0]
for index in range(1, len(nums)):
value = nums[index]
candidates = (value, high * value, low * value)
high, low = max(candidates), min(candidates)
best = min(best, low)
return best
For [2,3,-2,4,-1], the minimum is -48, ending before the final value. For [0,-2,0], it is -2.
Both adaptations avoid the input suffix copy and leave the input unchanged. They use arithmetic operations and a constant number of integer/index slots.
Growing product bits still determine numeric storage and multiplication cost. Neither adaptation accepts an empty list.
Transfer
Ask how the transition transforms ordering before compressing its candidates. Sign-dependent reversal requires both extremes; a more general nonmonotone transformation may require richer state.