CodeArchon

medium1-D Dynamic ProgrammingLinkedIn

Max Product Streaker

A trader finds the contiguous day streak with the highest cumulative multiplicative return.

Given an integer array, find the contiguous subarray with the largest product.

Choose approach

2
0
3
1
-2
2
4
3
i
1/4
Narrationstep 1 of 4

Init: maxP = minP = best = 2.

1def maxProduct(nums):
2 maxP = minP = best = nums[0]
3 for i in range(1, len(nums)):
4 x = nums[i]
5 tmp = max(x, x*maxP, x*minP)
6 minP = min(x, x*maxP, x*minP)
7 maxP = tmp
8 best = max(best, maxP)
9 return best
Variables
maxP=2
minP=2
best=2

How to think about it

  1. A negative × min = positive-max candidate.
  2. Reset to x alone when the chain shrinks the product.

Edge cases to catch in interview

  • Zero in the array breaks chains.
  • All negatives: even count of negs wins.

Examples

Example 10
{"nums":[-2,0,-1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed