House Robber (LeetCode 198): Solution and Explanation
Houses along a street each hold some amount of money, and you cannot take from two neighboring houses. Return the largest total you can collect.
Watch it run step by step
Try your own input and write the code →Intuition
Greedy ideas fail quickly here. Taking every other house starting from the first misses inputs like [2, 1, 1, 9], where the best plan is houses 0 and 3. Trying every subset of non-adjacent houses works but is exponential. The way forward is to make one decision at a time and notice that each decision only depends on a small amount of history.
Stand at house i and suppose you already know the best total for the houses before it. You have two options. Skip house i, in which case your total is the best for houses 0..i-1. Or rob house i, in which case you cannot have robbed house i - 1, so your total is nums[i] plus the best for houses 0..i-2. The answer for the first i + 1 houses is the larger of those two, which gives the recurrence best(i) = max(best(i - 1), nums[i] + best(i - 2)).
Since each value depends only on the two before it, you do not need a full table. The reference code keeps rob1 as the best total two houses back and rob2 as the best total one house back. For each house it computes the new best, then shifts the window forward: the old rob2 becomes rob1, and the new value becomes rob2. Starting both at 0 handles the first two houses naturally.
It is worth checking the recurrence on the smallest cases. With one house, the loop runs once and returns max(nums[0] + 0, 0), which is that house. With two houses, the second iteration compares robbing the second house alone against keeping the first, which is exactly the right choice, so no special cases are needed.
Approach: Dynamic programming with two rolling variables
- Set
rob1 = 0androb2 = 0, the best totals ending two houses back and one house back. - Loop over each amount
ninnums. - Compute
temp = max(n + rob1, rob2): either rob this house plus the best from two back, or skip it and keep the best from one back. - Shift the window:
rob1 = rob2, thenrob2 = temp. - After the loop,
rob2holds the best total over all houses, so return it.
Step-by-step example
nums = [2, 7, 9, 3, 1]
- n = 2: temp = max(2 + 0, 0) = 2. Now rob1 = 0, rob2 = 2.
- n = 7: temp = max(7 + 0, 2) = 7. Now rob1 = 2, rob2 = 7.
- n = 9: temp = max(9 + 2, 7) = 11. Now rob1 = 7, rob2 = 11.
- n = 3: temp = max(3 + 7, 11) = 11, so skipping this house is better. Now rob1 = 11, rob2 = 11.
- n = 1: temp = max(1 + 11, 11) = 12. Return 12, from robbing houses 0, 2 and 4 (2 + 9 + 1).
Code: Python, Java, C++
1class Solution:
2 def rob(self, nums: List[int]) -> int:
3 rob1, rob2 = 0, 0
4
5 for n in nums:
6 temp = max(n + rob1, rob2)
7 rob1 = rob2
8 rob2 = temp
9 return rob21class Solution {
2 public int rob(int[] nums) {
3 int rob1 = 0;
4 int rob2 = 0;
5
6 for (int n : nums) {
7 int temp = Math.max(n + rob1, rob2);
8 rob1 = rob2;
9 rob2 = temp;
10 }
11 return rob2;
12 }
13}1class Solution {
2public:
3 int rob(vector<int>& nums) {
4 int rob1 = 0;
5 int rob2 = 0;
6
7 for (int n : nums) {
8 int temp = max(n + rob1, rob2);
9 rob1 = rob2;
10 rob2 = temp;
11 }
12 return rob2;
13 }
14};Time and space complexity
O(n)
Each house is processed once with a constant number of operations.
O(1)
Only rob1, rob2 and the temporary value are kept, no matter how many houses there are.
Other approaches
DP array (time O(n), space O(n))
Store dp[i] for every prefix and fill it with the same recurrence. It uses more memory but makes it easy to reconstruct which houses were robbed by walking the table backward.
Top-down recursion with memoization (time O(n), space O(n))
Define rob(i) as the best from house i onward and return max(rob(i + 1), nums[i] + rob(i + 2)), caching results. It is often the easiest form to discover, but it uses recursion depth up to n.
Common mistakes
- Taking every other house, or comparing the sum of even indices with the sum of odd indices. The optimal plan can skip two houses in a row, as in [2, 1, 1, 9].
- Updating
rob1before computingtemp, which uses the wrong value from one house back instead of two. - Special-casing one or two houses and indexing
nums[1]on a single-element input. Starting both variables at 0 handles short arrays without any extra branches. - Applying this directly to houses arranged in a circle. There the first and last houses are adjacent, which needs two linear passes.
Frequently asked questions
What is the recurrence for House Robber?
best(i) = max(best(i - 1), nums[i] + best(i - 2)). You either skip house i and keep the previous best, or rob it and add the best from two houses back.
Why does a greedy approach fail for House Robber?
Picking the largest available house or alternating houses can block a better combination later. Only by comparing both choices at each house do you guarantee the optimum.
Can House Robber be solved in O(1) space?
Yes. The recurrence only looks back two positions, so two variables are enough, which is what this solution does.
How does House Robber II differ?
The houses form a circle, so the first and last are neighbors. Run this algorithm once excluding the last house and once excluding the first, then take the larger result.