←
Atlas · Dynamic programming · Topic 13 of 18

1-D Dynamic Programming

Write the answer for position i using answers for earlier positions, then fill them in once, left to right.

Spot it

Signals in the question

"Number of ways", "maximum / minimum total" along a single list.

Each step has a few choices (take or skip, 1 step or 2) and choices repeat.

A plain recursion recomputes the same subproblems again and again.

The idea

O(n) time · O(1) space

Name the subproblem: best(i) = the most money from the first i houses. At house i you either skip it (best(i−1)) or rob it (best(i−2) + its money). Keep only the last two answers as you walk.

Template · Take or skip

1def rob(nums):2    prev, curr = 0, 0   # best two houses back, best one back3    for money in nums:4        prev, curr = curr, max(curr, prev + money)5    return curr

The template, filled in for House Robber. The highlighted line is the part every problem of this kind shares.

The best, free

One of each
Watch1-D Dynamic Programming, explainedNeetCode · YouTube · freeReadIntroduction to dynamic programmingCP-Algorithms · free

Practice set

Loading your mission…

Common mistakes

1Starting to code before writing the recurrence in words.

2Wrong base cases (empty list, one item).

3Keeping a whole table when only the last one or two answers are needed.

Check yourself

Question 1 of 2

Climbing stairs, 1 or 2 steps at a time: ways(n) = ?