Algorithms · Dynamic programming

House Robber

Biggest total, never taking two neighbours.

The problem

A cat burglar walks down a row of houses with money in them, but alarms go off if two neighbouring houses are robbed. What’s the most money they can take?

best_take([1, 2, 3, 1])4
best_take([2, 7, 9, 3, 1])12
Dynamic programming. Write the answer down. A sticky note for every sum you’ve worked out, so you never work it out twice.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def best_take(houses):take the money in each house
def best_from(i):the best total from house i to the end
if i >= len(houses):past the last house
return 0nothing more to take
take = houses[i] + best_from(i + 2)take this one, skip its neighbour
skip = best_from(i + 1)or skip this one
return max(take, skip)whichever gives more
return best_from(0)start at the first house

Now ask: what if there were a billion?

Rules like “never two in a row” show up in scheduling: ad slots, shift rosters, which frames to keep in a video. They’re solved with the same running table, one step at a time.

Aim for O(n)🧩 classic

Think it through

At each house, what are your two choices?

  • Rob it, or skip it
  • Rob it, or rob the next one
Show the answer

Rob it, or skip it. Rob it (then the previous one must have been skipped) or skip it (keep the best so far).

Walking down the street once, what do you need to carry?

  • Every choice so far
  • Two numbers: best if I took the last house, best if I didn’t
Show the answer

Two numbers: best if I took the last house, best if I didn’t. Those two totals are enough to decide the next house. Dynamic programming often shrinks to “carry a couple of numbers forward”.

Stuck? 3 nudges, smallest first
  1. best_from(5) gets worked out again and again, by different paths. Count how often for 10 houses.
  2. Walk down the street once, keeping two numbers: the best total if you took the previous house, and if you didn’t.
  3. For each house: take, skip = skip + money, max(take, skip). The answer is max(take, skip).

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def best_take(houses):take the money in each house
take, skip = 0, 0best total if we took the last house, or didn't
for money in houses:walk down the street once
take, skip = skip + money, max(take, skip)take this one (so we skipped the last), or skip it
return max(take, skip)the better ending

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with dynamic programming