1-D Dynamic Programming
Dynamic programming is recursion that remembers. If a problem asks for the best value or the number of ways, and the same sub-question appears many times, you solve each sub-question once and build up. The 1-D kind needs only a single array (or a few variables).
When to reach for it
Section titled “When to reach for it”- The question asks for a maximum, minimum, or count of ways, not the actual choices.
- At each step you make a choice (take or skip, 1 step or 2, which coin).
- The brute force is exponential recursion where the same arguments repeat.
- The answer at position
idepends on earlier positions (i-1,i-2,i-coin). - Greedy fails on a small counterexample, so you must compare options.
Template
Section titled “Template”The recipe: define the state, write the recurrence, set base cases, pick the order, then shrink the space if only the last few values matter.
def solve(nums): n = len(nums) dp = [0] * (n + 1) # 1. state: dp[i] = answer for the first i items dp[0] = BASE # 3. base case(s) for i in range(1, n + 1): # 4. order: smaller subproblems first dp[i] = combine(dp[i - 1], ...) # 2. recurrence: from earlier states return dp[n] # 5. if dp[i] reads only dp[i-1], dp[i-2]: keep two variables insteadThe hard part is step 1. Say it in words first: “dp[i] is the best answer for …”.
Problems in this guide
Section titled “Problems in this guide”- Climbing Stairs — sum of the previous two counts
- House Robber — skip this house or rob it
- Maximum Subarray — extend the running sum or restart
- Coin Change — fewest coins per amount, built bottom-up
- Word Break — can each prefix be split into dictionary words
- Longest Increasing Subsequence — best length ending at each index