Learn / Dynamic programming

1D DP

In 1D DP the state is a single index: the best or the count for the first i items, or for step i. Each answer comes from a few earlier ones: the last step was 1 or 2 stairs, this house was robbed or skipped, this friend pairs up or stays single. Usually only the last few values are needed.

How to recognise it

  • A line of items or steps, and a decision at each one.
  • Counting ways to reach n, or the best total along a line.
  • A rule linking neighbours: no two adjacent, at most two in a row.

The pattern

best[0] = base
for i in 1..n:
    best[i] = combine(best[i - 1], best[i - 2], ... , item i)
ProblemRecurrence
climbing stairsf(i) = f(i-1) + f(i-2)
frog jumpf(i) = min over last jump of f(j) + cost(j, i)
house robberf(i) = max(f(i-1), f(i-2) + a[i])
friends pairingf(n) = f(n-1) + (n-1) f(n-2)
derangementsD(n) = (n-1)(D(n-1) + D(n-2))
painting the fencetrack "last two same" and "last two different"

Games

For "the player to move wins?", a position is winning when some move leads to a losing position for the opponent.

Common mistakes

  • Off-by-one errors in the base cases.
  • Keeping a whole table when two variables are enough (harmless, but wasteful).

Problems

0 of 13 solved

Check yourself

Ways to climb 5 stairs taking 1 or 2 at a time?

In House Robber, if you rob house i, which houses' best can you use?

How does House Robber II handle the circle?

Friends pairing: f(n) = f(n-1) + (n-1) × f(n-2). What does (n-1) count?