Skip to content
StackDecode
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

  1. Products behave differently from sums: two negatives multiply to a positive.
  2. So track both the largest and the smallest product of a subarray ending at each position.
  3. A negative item swaps the roles of max and min (a huge negative becomes a huge positive).
  4. The answer is the biggest "max" seen.

Watch it run

Loading animation…