
Quiz
Side Quest: Name the State
Every DP table starts with one sentence: "table[i] means …".
Get that sentence right and the rest follows. In Fill the Table,
ways[n] meant "the number of ways to reach stair n".
The second question is: which entries does table[i] need?
They must already be filled in, so the loop can build the table
in order, from small to big.
Gem hopping
Pip hops along a row of islands, collecting gems. Landing on two islands next to each other sets off an alarm. This DP finds the most gems Pip can collect:
gems = [2, 7, 9, 3, 1]
best = [0, gems[0]] # first 0 islands, first 1 island
for i in range(2, len(gems) + 1):
skip = best[i - 1] # leave island i-1
take = best[i - 2] + gems[i - 1] # take it, skip its neighbour
best.append(max(skip, take))
print(best[-1]) # 12 (2 + 9 + 1)
best[0] covers no islands, and best[1] covers just the first
one. Read the loop body to see what each new entry means.