House robber
medium 18 minPick houses along a street to maximise the money taken, never two neighbours.
Video lesson · Chapter 1 of 6
Two neighbors cannot both pay out
House robber in 75 seconds
1:27Reel
How it works
Step through the idea, or press Play.
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 .
| House | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Money | 2 | 7 | 9 | 3 | 1 |
| Best plan | rob | skip | rob | skip | rob |
[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 is off limits. Best total:
nums[i] + dp[i - 2].LEAVE house i
Skip it, and houses 0 to 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 , so nothing else needs checking.
The decision at house i
Every legal plan for the first three houses [2, 7, 9]
How many legal plans are there?
The recurrence
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
Best loot from houses 0 to i
Why the recurrence is right. Take the best plan for houses 0 to . Either it skips house , and then it is a plan for 0 to , so it is worth at most dp[i - 1]. Or it robs house , so it skips , and the rest is a plan for 0 to , 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
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)) # 12Calls made by rob(4) on [2, 7, 9, 3, 1]
rob(-1) to rob(4). The red part repeats work done elsewhere: overlapping subproblems.Counting the calls
Fix 1
Memoisation: answer each question once
One memoised call
i reaches the bottom box once. For 5 houses that is 9 calls instead of 15; in general , so time and space.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 12Fix 2
Tabulation: fill dp left to right
Filling dp for [2, 7, 9, 3, 1]
| i | nums[i] | skip = dp[i-1] | take = nums[i] + dp[i-2] | dp[i] | Decision |
|---|---|---|---|---|---|
| 0 | 2 | – | 2 | 2 | base: take |
| 1 | 7 | 2 | 7 | 7 | base: take the richer |
| 2 | 9 | 7 | 9 + 2 = 11 | 11 | take |
| 3 | 3 | 11 | 3 + 7 = 10 | 11 | skip |
| 4 | 1 | 11 | 1 + 11 = 12 | 12 | take |
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- 1Houses[2, 7, 9, 3, 1]
- 2Decidetake or leave
- 3Build dpbottom-up
- 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.
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 5Rolling variables
- space: two numbers whatever the street length.
- No base-case branches:
0, 0covers empty and single-house streets. - Gives the total only, not the list of houses.
Full dp table
- space for numbers that are read once and never again.
- Needs guards for
n == 0andn == 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 , so it was robbed: record it and jump back two. If dp[i] == dp[i - 1], house added nothing: step back one. At , the first house is in the plan.
The walk back
[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.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])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
[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
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])) # 4Comparison
Every approach and the family of problems
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute-force take or skip | , so | stack | Correct but hopeless past about 30 houses |
| Memoised recursion | memo + stack | Quick to write from the recurrence; depth limit applies | |
| dp table | Keeps every decision, so you can rebuild the plan | ||
| Two rolling variables | The default answer | ||
| Circular (House Robber II) | Two linear passes |
Problems with the same skeleton
| Problem | What changes | Recurrence idea |
|---|---|---|
| House Robber II | Houses in a circle | Max of two linear runs |
| House Robber III | Houses on a binary tree, parent and child adjacent | Each node returns (best with it, best without it) |
| Delete and Earn | Taking value v deletes v - 1 and v + 1 | Bucket the totals per value, then house robber on the buckets |
| Max sum of non-adjacent elements | Same problem, other name | Identical; with negatives, allow taking nothing |
| Paint House | Each house gets one of k colours, neighbours differ | dp[i][c] = cost + min over other colours |
| Shifts with a rest day | Pick days, rest the day after each | Identical to house robber |
Spotting the pattern
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.