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)
| Problem | Recurrence |
|---|---|
| climbing stairs | f(i) = f(i-1) + f(i-2) |
| frog jump | f(i) = min over last jump of f(j) + cost(j, i) |
| house robber | f(i) = max(f(i-1), f(i-2) + a[i]) |
| friends pairing | f(n) = f(n-1) + (n-1) f(n-2) |
| derangements | D(n) = (n-1)(D(n-1) + D(n-2)) |
| painting the fence | track "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
- Climbing Stairseasyguide ready
- Frog Jumpmediumguide ready
- Frog jump with K distancesmediumguide ready
- House Robbermediumguide ready
- House Robber IImediumguide ready
- Friends Pairing Problemmediumguide ready
- Painting the Fenceproblemmediumguide ready
- Maximize The Cut Segmentsmediumguide ready
- Maximum subsequence sum such that no three are consecutivemediumguide ready
- Maximum sum of pairs with specific differencemediumguide ready
- Maximum difference of zeros and ones in binary stringmediumguide ready
- Coin game winner where every player has three choicesmediumguide ready
- Count Derangements (Permutation such that no element appears in its original position)mediumguide ready