Maximum Product Subarray
Find the largest product of any contiguous subarray.
Why does this pattern fit?
Restate the exact job
Find the largest product of any contiguous subarray.
A negative value swaps the roles of largest and smallest ending products.
O(n) time · O(1) space
Tracking only the maximum loses a negative product that can become positive.
How to solve Maximum Product Subarray
The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.
What the question asks
Find the largest product of any contiguous subarray.
Why Dynamic programming fits
A negative value swaps the roles of largest and smallest ending products.
State to maintain
Maximum and minimum product ending here plus global best.
Transition
At each value consider value alone, value×oldMax, and value×oldMin.
Time and space
O(n) time · O(1) space
Counterexample to the tempting mistake
Tracking only the maximum loses a negative product that can become positive.
Prove it again tomorrow
Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.