sagelearnai

Dynamic Programming (1-D)

Signal: "number of ways", "minimum/maximum cost", "is it possible", over choices that build on smaller versions of the same problem, where brute-force recursion recomputes the same subproblems again and again.

Core idea: DP = recursion + memory. Two conditions make it work:

  1. Optimal substructure: the answer for i is built from answers to smaller subproblems.
  2. Overlapping subproblems: the same subproblems recur, so computing each once turns exponential time into polynomial time.

The 4-step recipe

  1. State: what does dp[i] mean? (Write it in one sentence. This is the hard part.)
  2. Recurrence: how does dp[i] depend on smaller states?
  3. Base cases.
  4. Order & answer: fill in an order where dependencies are ready; say which cell is the answer. Then optimize space if only the last few states are needed.
Naive recursion: fib(5) f5 f4 f3 f3 f2 f2 f1 f2 f1 f3 computed twice, f2 three times… O(2ⁿ) Bottom-up table: O(n) 11235 dp[i] = dp[i−1] + dp[i−2], each cell once
python
# Top-down (memoized recursion): often easiest to write first
from functools import cache
@cache
def f(i):
    if i <= 1: return base(i)
    return combine(f(i - 1), f(i - 2))

# Bottom-up (tabulation): no recursion limit, easy to space-optimize
dp = [0] * (n + 1)
dp[0], dp[1] = ...
for i in range(2, n + 1):
    dp[i] = combine(dp[i - 1], dp[i - 2])
FamilyStateExamples
Linear "steps"dp[i] = answer for the first i itemsClimbing Stairs, House Robber, Decode Ways
Unbounded knapsackdp[amount]Coin Change, Coin Change II
0/1 knapsackdp[capacity], iterate capacity backwardsPartition Equal Subset Sum
Subsequencedp[i] = best ending at iLongest Increasing Subsequence
String segmentationdp[i] = can prefix of length i be splitWord Break

Problems

  1. Climbing Stairs (Easy): ways(n) = ways(n−1) + ways(n−2)
  2. Min Cost Climbing Stairs (Easy): dp[i] = cost[i] + min(dp[i-1], dp[i-2]); answer min of last two
  3. House Robber (Medium): dp[i] = max(dp[i−1], dp[i−2] + nums[i])
  4. House Robber II (Medium): Circle → max(rob without last, rob without first)
  5. Longest Palindromic Substring (Medium): Expand around each of the 2n−1 centers
  6. Palindromic Substrings (Medium): Expand around each of the 2n−1 centers
  7. Decode Ways (Medium): Like stairs, but steps of 1 or 2 digits must be valid
  8. Coin Change (Medium): dp[a] = 1 + min(dp[a − coin])
  9. Coin Change II (Medium): Count combinations: loop coins outside, amounts inside
  10. Maximum Product Subarray (Medium): Track both max and min product ending here: a negative swaps them
  11. Word Break (Medium): dp[i] = some dp[j] and s[j:i] in dict
  12. Longest Increasing Subsequence (Medium): Patience sorting: tails[] + binary search
  13. Partition Equal Subset Sum (Medium): 0/1 knapsack to reach sum/2 (iterate capacity backwards)
  14. Combination Sum IV (Medium): Ordered sequences → loop target outside, nums inside
  15. Perfect Squares (Medium): Unbounded knapsack: dp[i] = 1 + min dp[i − j²]
  16. Delete and Earn (Medium): Bucket points by value → House Robber over values
  17. Fibonacci Number (Easy): Bottom-up with two rolling variables
  18. N-th Tribonacci Number (Easy): Three rolling variables
  19. Best Time to Buy and Sell Stock with Transaction Fee (Medium): Two states: cash (no stock) and hold; pay the fee on sell
  20. Wiggle Subsequence (Medium): up = down + 1 on a rise, down = up + 1 on a fall
  21. Integer Break (Medium): dp[i] = max over j of max(j, dp[j]) · (i − j); or math: as many 3s as possible
  22. Last Stone Weight II (Medium): Split stones into two groups with sums as equal as possible: 0/1 subset-sum
  23. Stone Game (Medium): Interval DP of score difference; (also: first player always wins with even piles)
  24. Minimum Cost For Tickets (Medium): dp[d] over calendar days: non-travel days copy dp[d−1]; travel days try 1/7/30 passes
  25. Best Time to Buy and Sell Stock III (Hard): Four states: buy1, sell1, buy2, sell2, updated in one pass
  26. Best Time to Buy and Sell Stock IV (Hard): Generalize Stock III to k (buy, sell) pairs; if k ≥ n/2 it's unlimited
  27. Russian Doll Envelopes (Hard): Sort by width asc, height DESC; LIS on heights with patience sorting