Array techniquesAnimated
Maximum Product Subarray
Track both the largest and smallest product ending here (negatives flip them).
Time
O(n)
Extra space
O(1)
Use it for
Contiguous product problems.
How it works
- Products behave differently from sums: two negatives multiply to a positive.
- So track both the largest and the smallest product of a subarray ending at each position.
- A negative item swaps the roles of max and min (a huge negative becomes a huge positive).
- The answer is the biggest "max" seen.
Watch it run
Loading animation…