mediumDynamic ProgrammingDynamic Programming

Maximum Product Subarray

mediumTime: O(n)Space: O(1)

Signals to notice

maximum product of contiguous subarraynegative numbers flip signboth min and max matter

Brute force first

Check every subarray's product. Computes each product from scratch without reusing previous results. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Track both current max and current min at each position. A negative number flips them — the most negative becomes the most positive when multiplied by a negative. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

At each element, the maximum product ending here is max(nums[i], maxSoFar * nums[i], minSoFar * nums[i]). You need both extremes because a negative can flip the minimum into the maximum. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Only tracking the maximum — negative × negative = positive, so the minimum product can suddenly become the maximum. You MUST track both. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Dynamic Programming Pattern