0:00 / 0:00

Rob the most cash from a row of houses without hitting two neighbours. Carry the best haul so far, one house at a time.

▼

The problem

A row of houses each holds some cash. Rob the most you can without robbing two adjacent houses.

Example: [2, 7, 9, 3, 1] → 12 (houses 1, 3 and 5).

def rob(houses):
    two_back, one_back = 0, 0
    for cash in houses:
        two_back, one_back = one_back, max(one_back, cash + two_back)
    return one_back
TRY IT ON LEETCODE ▶

The solution

def rob(houses):
    two_back, one_back = 0, 0
    for cash in houses:
        two_back, one_back = one_back, max(one_back, cash + two_back)
    return one_back

Transcript

House Robber. A street of houses, each holding some cash. You can rob as many as you like, but if you rob two houses next to each other, the alarm goes off. What's the most cash you can take without tripping it?

Take five houses holding two, seven, nine, three and one. Grabbing the biggest first fails: nine, then seven, right next door. The best haul is two, nine and one: twelve.

The brute force tries every safe set of houses. That count grows like the Fibonacci numbers: five houses have thirteen safe sets, but forty houses have over two hundred and sixty million. Far too slow.

Instead, stand at the last house and ask one question. Skip it, and your haul is the best from the houses before it. Rob it, and you add its cash to the best from two houses back, because its neighbor must stay untouched. Take whichever is bigger. Every house asks the same question, so answer them in order and write each answer down.

Walk left to right, keeping the best haul so far. The first house: two. The second: seven beats two, so seven. The third: skip it and keep seven, or rob it: nine plus two is eleven. Eleven wins. The fourth: keep eleven, or three plus seven is ten. Keep eleven. The last: keep eleven, or one plus eleven is twelve. Twelve is the answer.

In code, each step only looks two houses back, so two variables are enough. One holds the best up to the previous house, the other the best from the house before that. For each house, the new best is the bigger of skipping or robbing, and both variables shift forward.

One pass down the street, so the time is linear. And just two numbers, however long the street, so the space is constant.

Skip it or rob it, and remember the best. That's House Robber.