Classic DP Problems
1. Coin change (fewest coins)
- State:
dp[a]= the fewest coins to make amounta. - Transition:
dp[a] = min(dp[a - c] + 1)for each coinc ≤ a. - Base:
dp[0] = 0. O(amount × coins).
2. 0/1 knapsack
Items have a weight and a value; the bag holds weight W, and each item is taken at most once.
- State:
dp[w]= the best value with capacityw. - Loop items, and for each loop
wfrom W down to the item's weight:dp[w] = max(dp[w], dp[w - weight] + value). Going downwards prevents reusing an item.
3. Longest common subsequence (LCS)
The longest sequence appearing in both strings in order (not necessarily touching). Used in diff tools and DNA comparison.
- State:
dp[i][j]= the LCS of the firstiletters of A and the firstjof B. - If the letters match:
dp[i-1][j-1] + 1; otherwisemax(dp[i-1][j], dp[i][j-1]).
4. Longest increasing subsequence (LIS)
- O(n²) DP:
dp[i] = 1 + max(dp[j])forj < iwitha[j] < a[i]. - O(n log n) with binary search (patience sorting).
Recognising the type
| Clue | Pattern |
|---|---|
| a sequence, a decision at each step | 1D DP |
| two strings or a grid | 2D DP |
| pick items under a limit | knapsack |
| count paths in a grid | dp[r][c] = dp[r-1][c] + dp[r][c-1] |
Example
import bisect
def coin_change(coins, amount):
dp = [0] + [float("inf")] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
dp[a] = min(dp[a], dp[a - c] + 1)
return -1 if dp[amount] == float("inf") else dp[amount]
def knapsack(items, capacity): # items: (weight, value)
dp = [0] * (capacity + 1)
for weight, value in items:
for w in range(capacity, weight - 1, -1):
dp[w] = max(dp[w], dp[w - weight] + value)
return dp[capacity]
def lcs(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
dp[i][j] = (dp[i-1][j-1] + 1 if a[i-1] == b[j-1]
else max(dp[i-1][j], dp[i][j-1]))
return dp[-1][-1]
def lis(nums): # O(n log n)
tails = []
for x in nums:
i = bisect.bisect_left(tails, x)
tails[i:i + 1] = [x]
return len(tails)
print(coin_change([1, 2, 5], 11)) # 3
print(knapsack([(1, 1), (3, 4), (4, 5), (5, 7)], 7)) # 9
print(lcs("ABCBDAB", "BDCABA")) # 4
print(lis([10, 9, 2, 5, 3, 7, 101, 18])) # 4