#152
Medium
Dynamic Programming

Maximum Product Subarray

Find the contiguous subarray with the maximum product.

ArrayDP

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

1

Unlike sum DP, product DP must track both the best and worst product ending here because a negative value can swap roles instantly.

2

The current negative number can turn the previous minimum into the new maximum.

3

Name the state in plain language.

4

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

warning

Tracking only the current maximum and losing negative-flip information.

warning

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.

view_weekBack to the pattern page
LeetCode 152. Maximum Product Subarray Guide | Interview AiBox