You already know memoization from the Complexity lesson: storing the results of a recursive function to avoid repeating calculations. Dynamic programming (DP) generalizes the idea: a large problem is solved from smaller subproblems that repeat, storing each answer only once.
The four steps
- State: what data identifies a subproblem (for example, “the first
ihouses”). - Recurrence: how a state is computed from smaller ones.
- Base case: the states that are known without computing (empty is worth 0).
- Order: compute the states so that the ones needed are already done.
Top-down and bottom-up
The house robber problem (you cannot rob two adjacent houses) shows both ways: the recursive one with lru_cache and the table filled in order.
from functools import lru_cache
# Approach 1: recursion + memoization (top-down)
@lru_cache(maxsize=None)
def max_loot(houses, i):
if i < 0:
return 0
return max(max_loot(houses, i - 1), # skip house i
max_loot(houses, i - 2) + houses[i]) # rob it
print(max_loot((2, 7, 9, 3, 1), 4)) # 12
# Approach 2: table (bottom-up)
def max_loot_table(houses):
dp = [0] * (len(houses) + 1) # dp[i]: best loot with the first i houses
for i in range(1, len(houses) + 1):
rob = dp[i - 2] + houses[i - 1] if i >= 2 else houses[i - 1]
dp[i] = max(dp[i - 1], rob)
return dp[-1]
print(max_loot_table([2, 7, 9, 3, 1])) # 12
The table version avoids recursion (and its depth limit) and is usually faster; the memoized one is easier to write when not all states are needed. To decide whether a problem is DP ask yourself: do the subproblems repeat? Is the best solution built from the best solutions of the parts?
You practice it in The house robber.