Maximum Product Subarray – Solution & Complexity
Solution Walkthrough
Step 1: Understand why sign changes matter
- Products behave differently from sums because multiplying by a negative flips the sign.
- A very small negative running product can become the best positive answer after another negative value.
Step 2: Brute-force every starting point
- Start each subarray at every index and keep multiplying as you extend the right edge.
- This checks all
O(n^2)contiguous subarrays and is correct, but too slow for long inputs.
Step 3: Keep both extremes at each position
- Let
max_endingbe the largest product ending at the current index. - Let
min_endingbe the smallest product ending there, because a future negative number may flip it into the new maximum.
- Let
Step 4: Update the running max and min in one pass
- When the current number is negative, swap the running extremes before multiplying.
- Then decide whether to start fresh at
numor extend the previous product.
Step 5: Dry run / state trace
Trace
nums = [2, 3, -2, 4].num max_ending before min_ending before max_ending after min_ending after best 2 2 2 2 2 2 3 2 2 6 3 6 -2 6 3 -2 -12 6 4 -2 -12 4 -48 6 The negative
-2destroys the running maximum but creates a much smaller negative product, which is exactly why the minimum track is necessary.Step 6: Final solution and complexity
Track the largest and smallest products ending at each index; one pass gives
O(n)time andO(1)space.