Part 17 / Topic 19 of 20
Dynamic programming
Dynamic programming (DP) solves a problem by breaking it into smaller, overlapping subproblems, solving each one only once, and reusing the stored answer every time it is needed again. Two ways to store answers: memoisation (recursion, cached, top-down) and tabulation (an explicit table, built bottom-up). DP turns naive exponential recursion into something far cheaper, trading a bit of memory for a lot of time. Every DP has four parts, and naming them beats memorising problem lists: the state (what a subproblem is ā "ways to climb n stairs"), the transition (how bigger states come from smaller ones ā ways(n) = ways(nā1) + ways(nā2)), the base case (the state you can answer outright), and the order (solve smaller states before anything that needs them). The examples below climb the usual ladder: one-dimensional, then a grid, then choose-or-skip (knapsack), then two sequences. Think of planning a festival shopping budget: once you have worked out "the best way to spend exactly ā¹500," you reuse that answer every time ā¹500 shows up again inside a bigger plan, instead of re-figuring it out from scratch.
from functools import cache
def fib_naive(n): # O(2^n): repeats the same sub-calls over and over
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
@cache
def fib_memo(n): # O(n): @cache remembers every answer it has seen
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
Timed for fib(28):
fib(28) naive : 317811, took 20.7 ms
fib(28) memoised: 317811, took 0.008 ms (varies by machine)
Over 2,000x faster for the same answer, purely by not solving the same subproblem twice - the same functools.cache tool Part 14 used for shipping_cost.
A classic tabulation example - climbing stairs 1 or 2 steps at a time - builds the answer bottom-up without recursion at all:
def climbing_stairs(steps):
"""ways(n) = ways(n-1) + ways(n-2): the last move was a 1-step or a 2-step."""
if steps <= 1:
return 1
previous, current = 1, 1
for _ in range(2, steps + 1):
previous, current = current, previous + current
return current
print(climbing_stairs(5)) # 8
print(climbing_stairs(10)) # 89
A grid state has two coordinates ā the cheapest path across a toll grid, moving only right or down:
def cheapest_path(costs):
rows, cols = len(costs), len(costs[0])
best = [row.copy() for row in costs]
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
continue
from_above = best[r - 1][c] if r > 0 else float("inf")
from_left = best[r][c - 1] if c > 0 else float("inf")
best[r][c] += min(from_above, from_left)
return best[-1][-1]
print(cheapest_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7
State: best[r][c], the cheapest way to reach that cell. Transition: the cell's own toll plus the cheaper of "from above" and "from the left". Base case: the start cell. Order: row by row ā both ingredients are always ready.
Real-world example: Asha is packing a travel bag with a 10kg weight limit and must choose which items to take to maximise their total value - the classic 0/1 knapsack problem. A table table[w] tracks "the best value achievable with a bag of capacity w", filled in item by item:
def pack_travel_bag(items, capacity):
table = [0] * (capacity + 1)
for name, weight, value in items:
for w in range(capacity, weight - 1, -1): # backwards: each item used once
table[w] = max(table[w], table[w - weight] + value)
return table[capacity]
items = [("laptop", 3, 900), ("camera", 2, 500), ("books", 4, 300),
("shoes", 2, 250), ("snacks", 3, 200)]
print(pack_travel_bag(items, 10)) # 1850
Checking every subset by brute force would be O(2āæ) for n items; this DP table is O(items Ć capacity). The last rung, two sequences, gives the state two prefixes: table[i][j] = the longest common subsequence of a[:i] and b[:j] ā for "sunday" and "saturday" it is 5 ("suday"); the full table version is in the example program.
ā ļø Memoising a function that is not pure (same input always gives the same output, no side effects) silently returns stale results. Recursion without
@cache/lru_cacheon a problem with overlapping subproblems (Fibonacci, path-counting, knapsack) quietly becomes exponential - if recursion "feels slow for no reason," check for repeated sub-calls first.
Practice: counting or minimising steps (coin change, climbing stairs, minimum notes for exact change); string comparison DP (longest common subsequence, edit distance style problems); 0/1 knapsack style choose-or-skip optimisation under a limit.
Practice on LeetCode - start here: Climbing Stairs Ā· Min Cost Climbing Stairs Ā· House Robber Ā· Maximum Subarray Ā· Coin Change Ā· Partition Equal Subset Sum
Show the full practice list (21 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Fibonacci Number | Easy |
| N-th Tribonacci Number | Easy |
| Pascal's Triangle II | Easy |
| Delete and Earn | Medium |
| Unique Paths | Medium |
| Minimum Path Sum | Medium |
| Triangle | Medium |
| Perfect Squares | Medium |
| House Robber II | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Maximum Product Subarray | Medium |
| Longest Increasing Subsequence | Medium |
| Coin Change II | Medium |
| Word Break | Medium |
| Decode Ways | Medium |
| Target Sum | Medium |
| Palindromic Substrings | Medium |
| Longest Palindromic Substring | Medium |
| Longest Palindromic Subsequence | Medium |
| Best Time to Buy and Sell Stock with Cooldown | Medium |
| Edit Distance | Medium |
| Regular Expression Matching | Hard |
Full program: examples/19_dynamic_programming.py.
Exercise 19: Dynamic programming ā minimum notes for exact change
Scenario: A shopkeeper's cash drawer has an unlimited supply of ā¹1, ā¹2, ā¹5 and ā¹10 notes, and wants the FEWEST notes that add up to exactly a given amount.
What to do: Write min_notes(denominations: list[int], amount: int) -> int | None using bottom-up DP: table[a] = fewest notes to make amount a, built from table[0] = 0 upward; table[a] = 1 + min(table[a - d] for d in denominations if d <= a and table[a - d] is not None); return None if amount cannot be made exactly. Print the answer for amounts 7 and 3 using denominations [1, 2, 5, 10], then for amount 3 using only [2, 5] (impossible).
Sample output:
Fewest notes for 7 using [1, 2, 5, 10]: 2
Fewest notes for 3 using [1, 2, 5, 10]: 2
Fewest notes for 3 using [2, 5]: None
Show the solution to Exercise 19
"""Exercise 19: Dynamic programming - minimum notes for exact change.
Run: python ex12.py (macOS/Linux: python3 ex12.py)
"""
def min_notes(denominations: list[int], amount: int) -> int | None:
table: list[int | None] = [0] + [None] * amount
for a in range(1, amount + 1):
best = None
for d in denominations:
if d <= a and table[a - d] is not None:
candidate = 1 + table[a - d]
if best is None or candidate < best:
best = candidate
table[a] = best
return table[amount]
def main() -> None:
print("Fewest notes for 7 using [1, 2, 5, 10]:", min_notes([1, 2, 5, 10], 7))
print("Fewest notes for 3 using [1, 2, 5, 10]:", min_notes([1, 2, 5, 10], 3))
print("Fewest notes for 3 using [2, 5]:", min_notes([2, 5], 3))
if __name__ == "__main__":
main()