Maximum Product Subarray
Contiguous subarray with the largest product. Negatives and zeros lurk in the array.
Open on LeetCode ↗Intuition
Kadane's trick almost works, but a negative number flips the world: the smallest (most negative) product so far becomes the biggest after multiplying by a negative. So track two running values — the max AND the min product ending here. Each new element either starts fresh or extends one of them; a zero resets both.
Approach
Why plain Kadane breaks
With sums, a bigger prefix is always better. With products, [-2, 3, -4]: the best answer 24 routes through the most negative prefix −6. Discarding minima loses the answer.
Track a (max, min) pair
For each x: candidates are {x, x·curMax, x·curMin}. New curMax = max of them, new curMin = min of them. A negative x swaps the roles — which is exactly why both are kept.
Answer is the best curMax seen
Update the global answer each step. Zeros make both candidates collapse toward x=0, restarting the window naturally.
Solution & live demo
Edge cases
Answer is that element — 'start fresh at x' candidate covers it.
Both trackers pass through 0 and restart after it.
The min-tracker carries the odd-negative prefix until a second negative flips it positive.