Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 152 Maximum Product Subarray - Why It's Tricky

Negative numbers twist

Here is the twist: multiplying two negatives gives a positive. So the most negative product at position i1i-1 might become the most positive at position ii. Consider [2,3,4][-2, 3, -4]. The product of all three is 2424, which is positive.

But If only tracked the maximum product ending at each position, you would miss this. At index 11, the max product ending there is 33 (just the element itself). You would discard the 2-2. But that 2-2 is critical for the final answer.

Why a simple Kadane-style approach fails. You cannot track the maximum. negative products too, because they might become positive later. Zero is another edge case. Any subarray containing zero has product zero. So zero acts as a "reset point". You must start fresh after it.