6 / 75
Medium
Maximum Product Subarray
#6arraydynamic-programming
Track both max and min products at each position, swapping when encountering negatives to handle sign flips.
Example:
Input:
[2,3,-2,4]Output:
6 (subarray [2,3] has the largest product)Common Mistakes:
- Only tracking maximum product without tracking minimum (fails when negative numbers create larger products)
- Not resetting product chain when encountering zero
- Forgetting to swap max/min when current number is negative
Notes:
Key insight: negative numbers flip signs, so the minimum product can become maximum. Always consider starting fresh from current element vs. extending previous products.
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Track both max and min products at each position, swapping when encountering negatives to handle sign flips.
Example:
Input:
[2,3,-2,4]Output:
6 (subarray [2,3] has the largest product)Common Mistakes:
- Only tracking maximum product without tracking minimum (fails when negative numbers create larger products)
- Not resetting product chain when encountering zero
- Forgetting to swap max/min when current number is negative
Notes:
Key insight: negative numbers flip signs, so the minimum product can become maximum. Always consider starting fresh from current element vs. extending previous products.
6/75
Maximum Product Subarray