Skip to content
mlmentorship

Maximum Product Subarray

Keep both ending-product extremes because a negative multiplier reverses which one can win.

Published · 12 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Maximum Product Subarray

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Track both extreme products ending at each index because multiplying by a negative swaps which extreme can become largest.

Problem trace

A very negative product can become the next positive maximum

Worked example: a negative minimum becomes a positive maximum after a sign flipFor (-2,3,-4), the previous minimum -6 becomes 24 after multiplying by -4. Retaining only the previous maximum would lose this answer.The same negative multiplier -4reverses extrema orderprevious max3-12new minprevious min-624new maxAll candidates: standalone -4,old-max product -12, old-min product24.Keep both prior extrema; the oldminimum supplies the winner.
Read it this way: For (-2,3,-4), the previous minimum -6 becomes 24 after multiplying by -4. Retaining only the previous maximum would lose this answer. Which twenty-four-point candidate disappears if only the previous maximum is retained?
Full interview answer 12 min read

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

Input and goalFind the largest product of a nonempty continuous subarray.
Initialize both extremesAt index 0, the only ending product is 2, so current_max=current_min=best=2.
scan2031-2243-14
processedPrefix[0..0]endingRange[2]arithmeticmax=2; min=2; best=2
scan
0
processed prefix
[0..0]
ending range
[2]

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.
At index 0, the only ending product is 2, so current_max=current_min=best=2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the algorithm retain -48 before reading -1, even though -48 is far from the current best product?
Reference drawing

Problem trace

A very negative product can become the next positive maximum

Worked example: a negative minimum becomes a positive maximum after a sign flipFor (-2,3,-4), the previous minimum -6 becomes 24 after multiplying by -4. Retaining only the previous maximum would lose this answer.The same negative multiplier -4reverses extrema orderprevious max3-12new minprevious min-624new maxAll candidates: standalone -4,old-max product -12, old-min product24.Keep both prior extrema; the oldminimum supplies the winner.
Execution trace
Input and goalFind the largest product of a nonempty continuous subarray.
Initialize both extremesAt index 0, the only ending product is 2, so current_max=current_min=best=2.
scan2031-2243-14
processedPrefix[0..0]endingRange[2]arithmeticmax=2; min=2; best=2
scan
0
processed prefix
[0..0]
ending range
[2]

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.
At index 0, the only ending product is 2, so current_max=current_min=best=2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the algorithm retain -48 before reading -1, even though -48 is far from the current best product?
Read it this way: For (-2,3,-4), the previous minimum -6 becomes 24 after multiplying by -4. Retaining only the previous maximum would lose this answer. Which twenty-four-point candidate disappears if only the previous maximum is retained?

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.