AlgoViz

House robber

medium 18 min

Pick houses along a street to maximise the money taken, never two neighbours.

Video lesson · Chapter 1 of 6

Two neighbors cannot both pay out

0:00 / 5:34

House robber in 75 seconds

1:27Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Choose at each house. Take it (nums[i] + best up to i - 2) or skip it (best up to i - 1)

Understand it

Start here

The problem: a street of alarms

Houses stand in a row and each holds some money, given as a list nums of non-negative numbers. Neighbouring houses share an alarm: rob two adjacent houses on the same night and the police come. Return the most money you can take without setting it off. For nums = [2, 7, 9, 3, 1] the answer is 12: houses 0, 2 and 4, so 2+9+12 + 9 + 1.

House01234
Money27931
Best planrobskiprobskiprob
The best plan for [2, 7, 9, 3, 1] skips the second richest house (7) and still robs the 1 at the end.

This is the classic first problem where a dynamic programming state carries a decision. It has the same two-back shape as Climbing stairs and Fibonacci, with a max where they have a +. The general method lives in Dynamic programming: the core idea.

The choice

Take or skip each house

  • TAKE house i

    Rob it, so house i−1i - 1 is off limits. Best total: nums[i] + dp[i - 2].

  • LEAVE house i

    Skip it, and houses 0 to i−1i - 1 are free to use. Best total: dp[i - 1].

  • Choose the MAX

    dp[i] is the bigger of the two. Nothing else can happen at house ii, so nothing else needs checking.

The decision at house i

Two options, one comparison, one stored number per house.

Every legal plan for the first three houses [2, 7, 9]

Five legal plans; the green path is the best, 11. Taking a house forces a skip at the next one, which prunes the tree.

How many legal plans are there?

P(n)=P(n−1)⏟skip house n−1+P(n−2)⏟take it,P(0)=1, P(1)=2  ⟹  P(n)=F(n+2)P(n) = \underbrace{P(n-1)}_{\text{skip house } n-1} + \underbrace{P(n-2)}_{\text{take it}}, \quad P(0) = 1,\ P(1) = 2 \;\Longrightarrow\; P(n) = F(n+2)
For 5 houses that is F(7)=13F(7) = 13 legal plans out of 25=322^5 = 32 subsets; for 40 houses about 267 million. Too many to list, but each is built from smaller plans, which is what DP exploits.

The recurrence

dp[i] = max(dp[i-1], dp[i-2] + nums[i])

Best loot from houses 0 to i

dp[i]={nums[0]i=0max⁡(nums[0], nums[1])i=1max⁡(dp[i−1], dp[i−2]+nums[i])i≥2\text{dp}[i] = \begin{cases} \text{nums}[0] & i = 0 \\ \max(\text{nums}[0],\ \text{nums}[1]) & i = 1 \\ \max\big(\text{dp}[i-1],\ \text{dp}[i-2] + \text{nums}[i]\big) & i \ge 2 \end{cases}
The answer is dp[n−1]\text{dp}[n-1]. With dp[−1]=dp[−2]=0\text{dp}[-1] = \text{dp}[-2] = 0 the two base cases follow from the general rule.

Why the recurrence is right. Take the best plan for houses 0 to ii. Either it skips house ii, and then it is a plan for 0 to i−1i - 1, so it is worth at most dp[i - 1]. Or it robs house ii, so it skips i−1i - 1, and the rest is a plan for 0 to i−2i - 2, worth at most dp[i - 2]. Both totals are reachable, so the best is their max. A best answer built from best answers to smaller prefixes is optimal substructure.

Brute force

The take-or-skip tree and its cost

Python
def rob(nums, i):    """Most money from houses 0..i."""    if i < 0:        return 0    if i == 0:        return nums[0]    skip = rob(nums, i - 1)    take = nums[i] + rob(nums, i - 2)    return max(skip, take)houses = [2, 7, 9, 3, 1]print(rob(houses, len(houses) - 1))   # 12
The recurrence written as plain recursion. Correct, and exponential.
Edit and run it in your browser

Calls made by rob(4) on [2, 7, 9, 3, 1]

15 calls for 6 distinct questions, rob(-1) to rob(4). The red part repeats work done elsewhere: overlapping subproblems.

Counting the calls

C(i)=C(i−1)+C(i−2)+1,C(0)=C(−1)=1  ⟹  Cn houses=2F(n+1)−1=Θ(φn),  φ=1+52≈1.618C(i) = C(i-1) + C(i-2) + 1,\quad C(0) = C(-1) = 1 \;\Longrightarrow\; C_{\text{n houses}} = 2F(n+1) - 1 = \Theta(\varphi^{n}),\ \ \varphi = \tfrac{1+\sqrt{5}}{2} \approx 1.618
15 calls for 5 houses, 177 for 10, 21,891 for 20 and 331,160,281 for 40: exactly the Fibonacci call tree. Quoted as O(2n)O(2^n) time, with O(n)O(n) stack space.

Fix 1

Memoisation: answer each question once

One memoised call

Each i reaches the bottom box once. For 5 houses that is 9 calls instead of 15; in general 2n−12n - 1, so O(n)O(n) time and O(n)O(n) space.
Python
from functools import cachedef rob_memo(nums):    @cache    def best(i):                      # best from houses 0..i        if i < 0:            return 0        return max(best(i - 1), nums[i] + best(i - 2))    return best(len(nums) - 1)def rob_forward(nums):    memo = {}    def helper(i):                    # best from houses i..end        if i >= len(nums):            return 0        if i in memo:            return memo[i]        take = nums[i] + helper(i + 2)        leave = helper(i + 1)        memo[i] = max(take, leave)        return memo[i]    return helper(0)print(rob_memo([2, 7, 9, 3, 1]), rob_forward([2, 7, 9, 3, 1]))   # 12 12
Two memoised versions: looking back from the last house, and the original app's version looking forward from the first.
Edit and run it in your browser

Fix 2

Tabulation: fill dp left to right

Filling dp for [2, 7, 9, 3, 1]

inums[i]skip = dp[i-1]take = nums[i] + dp[i-2]dp[i]Decision
02–22base: take
17277base: take the richer
2979 + 2 = 1111take
33113 + 7 = 1011skip
41111 + 11 = 1212take
Each row reads two numbers that are already in the table. The answer is the last cell, 12.
Python
def rob_table(nums):    n = len(nums)    if n == 0:        return 0    if n == 1:        return nums[0]    dp = [0] * n    dp[0] = nums[0]    dp[1] = max(nums[0], nums[1])    for i in range(2, n):        dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])    return dp[n - 1]for street in ([2, 7, 9, 3, 1], [1, 2, 3, 4, 5], [5, 1, 5, 1, 5], [2, 1]):    print(street, rob_table(street))   # 12, 9, 15, 2
Bottom-up with a dp list: O(n)O(n) time, O(n)O(n) space, no recursion.
Edit and run it in your browser
The whole method
  1. 1Houses[2, 7, 9, 3, 1]
  2. 2Decidetake or leave
  3. 3Build dpbottom-up
  4. 4Maximumdp[n-1] = 12

Fix 3

Two rolling variables: O(1) space

Look at what one step reads: dp[i - 1] and dp[i - 2], nothing older. So keep two numbers: prev1, the best up to the previous house, and prev2, the best up to the one before. Starting both at 0 means an empty street returns 0 and a single house returns its value, with no special cases.

Python
def rob(nums):    prev2, prev1 = 0, 0               # best up to i-2, best up to i-1    for x in nums:        prev2, prev1 = prev1, max(prev1, prev2 + x)    return prev1print(rob([2, 7, 9, 3, 1]))   # 12print(rob([]), rob([5]))      # 0 5
The version to write in an interview: O(n)O(n) time, O(1)O(1) space.
Edit and run it in your browser

Rolling variables

  • O(1)O(1) space: two numbers whatever the street length.
  • No base-case branches: 0, 0 covers empty and single-house streets.
  • Gives the total only, not the list of houses.

Full dp table

  • O(n)O(n) space for numbers that are read once and never again.
  • Needs guards for n == 0 and n == 1.
  • But keep it when you must report which houses were robbed.

Reconstruction

Which houses were robbed?

The table holds every decision. Walk it backwards from the last house: if dp[i] > dp[i - 1], the total grew at house ii, so it was robbed: record it and jump back two. If dp[i] == dp[i - 1], house ii added nothing: step back one. At i=0i = 0, the first house is in the plan.

The walk back

On [2, 7, 9, 3, 1]: 12 ≠ 11 take 4, jump to 2; 11 ≠ 7 take 2, jump to 0; take 0. Plan: houses 0, 2, 4.
Python
def rob_with_plan(nums):    if not nums:        return 0, []    n = len(nums)    dp = [0] * n    for i in range(n):        skip = dp[i - 1] if i >= 1 else 0        take = nums[i] + (dp[i - 2] if i >= 2 else 0)        dp[i] = max(skip, take)    picked, i = [], n - 1    while i >= 0:        if i == 0 or dp[i] != dp[i - 1]:            picked.append(i)            i -= 2        else:            i -= 1    return dp[-1], picked[::-1]print(rob_with_plan([2, 7, 9, 3, 1]))          # (12, [0, 2, 4])print(rob_with_plan([4, 1, 2, 7, 5, 3, 1]))    # (14, [0, 3, 5])
Total and plan together, in O(n)O(n) time and space.
Edit and run it in your browser

Extension

House Robber II: a circular street

Now the street is a circle, so the first and last houses are neighbours too. No plan can rob both. So every legal plan either leaves out the last house or leaves out the first one, and each of those is an ordinary straight street. Solve both and take the better.

Breaking the circle

On [2, 7, 9, 3, 1]: case 1 [2, 7, 9, 3] gives 11, case 2 [7, 9, 3, 1] gives 10, so the circle gives 11, down from 12.

The circular answer

rob∘(a0,…,an−1)=max⁡(rob(a0,…,an−2), rob(a1,…,an−1)),n≥2\text{rob}_{\circ}(a_0, \dots, a_{n-1}) = \max\big(\text{rob}(a_0, \dots, a_{n-2}),\ \text{rob}(a_1, \dots, a_{n-1})\big), \qquad n \ge 2
Two linear passes: still O(n)O(n) time and O(1)O(1) space. For n=1n = 1 return a0a_0, because both slices are empty.
Python
def rob_line(houses):    prev2, prev1 = 0, 0    for x in houses:        prev2, prev1 = prev1, max(prev1, prev2 + x)    return prev1def rob_circle(nums):    if len(nums) == 1:        return nums[0]    return max(rob_line(nums[:-1]), rob_line(nums[1:]))print(rob_circle([2, 7, 9, 3, 1]))   # 11print(rob_circle([2, 3, 2]))         # 3print(rob_circle([1, 2, 3, 1]))      # 4
House Robber II with the rolling-variable helper.
Edit and run it in your browser

Comparison

Every approach and the family of problems

ApproachTimeSpaceNotes
Brute-force take or skipΘ(φn)\Theta(\varphi^n), so O(2n)O(2^n)O(n)O(n) stackCorrect but hopeless past about 30 houses
Memoised recursionO(n)O(n)O(n)O(n) memo + stackQuick to write from the recurrence; depth limit applies
dp tableO(n)O(n)O(n)O(n)Keeps every decision, so you can rebuild the plan
Two rolling variablesO(n)O(n)O(1)O(1)The default answer
Circular (House Robber II)O(n)O(n)O(1)O(1)Two linear passes
Every DP version does one comparison per house.

Problems with the same skeleton

ProblemWhat changesRecurrence idea
House Robber IIHouses in a circleMax of two linear runs
House Robber IIIHouses on a binary tree, parent and child adjacentEach node returns (best with it, best without it)
Delete and EarnTaking value v deletes v - 1 and v + 1Bucket the totals per value, then house robber on the buckets
Max sum of non-adjacent elementsSame problem, other nameIdentical; with negatives, allow taking nothing
Paint HouseEach house gets one of k colours, neighbours differdp[i][c] = cost + min over other colours
Shifts with a rest dayPick days, rest the day after eachIdentical to house robber

Spotting the pattern

The same take-or-skip decision, adapted to the shape of the input.

Recap

Key takeaways

Key points

  • dp[i] is the most money from houses 0 to i; the answer is dp[n - 1].
  • At each house: skip it, dp[i - 1], or take it, dp[i - 2] + nums[i]. dp[i] is the max.
  • Base cases: dp[0] = nums[0] and dp[1] = max(nums[0], nums[1]).
  • Greedy and every-other-house both fail; the take-or-skip recurrence does not.
  • Brute force makes 2F(n + 1) - 1 calls, Θ(φⁿ); memo or table gives O(n) time.
  • Two rolling variables, updated together, give O(1) space and handle empty and single-house streets.
  • Keep the table to rebuild the plan: dp grew means taken (jump two), equal means skipped (step one).
  • House Robber II: max of the street without its last house and without its first.

Sources