Maximum Product Subarray — dynamic programming
Each answer is a combination of smaller answers already in the table. Built for LeetCode 152. Maximum Product Subarray.
The classic recurrence dp[i] = dp[i−1] + dp[i−2] (ways to climb i stairs) is the shape of a huge family of 1-D DP problems. Fill left to right; two rolling variables are enough.
Algorithm
- Base:
a, b = 1, 1(ways to reach step 0 and 1). - For
ifrom 2 ton,a, b = b, a+b. - Return
b.
- Time
- O(n)
- Space
- O(1)
class Solution: def maximumProductSubarray(self, n: int) -> int: a, b = 1, 1 for _ in range(2, n + 1): a, b = b, a + b return b