Maximum Product Subarray
Find the contiguous subarray with the maximum product.
Pattern fit
Unlike sum DP, product DP must track both the best and worst product ending here because a negative value can swap roles instantly.
Key observation
The current negative number can turn the previous minimum into the new maximum.
Target complexity
O(n) / O(1)
How to break down the solution cleanly
Unlike sum DP, product DP must track both the best and worst product ending here because a negative value can swap roles instantly.
The current negative number can turn the previous minimum into the new maximum.
Name the state in plain language.
List the decisions that can transition into the state.
Reference implementation
Python# Generic pattern template
# 1D DP
dp = [0] * (n + 1)
dp[0] = base
for i in range(1, n + 1):
dp[i] = transition(dp, i)
# 2D DP
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = transition(dp, i, j)
Common pitfalls
Tracking only the current maximum and losing negative-flip information.
Updating max before min and corrupting the rolling state.
Common follow-ups
Why does a negative number require two states?
How does zero split the problem into segments?
Continue with related problems
Build repeatable depth inside the Dynamic Programming cluster before moving on.