House Robber
Medium
Topics
You are a robber planning to rob houses along a street. You cannot rob two adjacent houses. Given nums (money in each house), return the maximum you can rob without alerting the police.
Example 1
robbed
The shaded houses total 4 and no two are adjacent. At each house the choice is only between taking it plus the best up to two back, or skipping it and keeping the best up to one back — so two running numbers replace the whole table.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,2,3,1] Output: 4
Example 2
robbed
Input: nums = [2,7,9,3,1] Output: 12
Constraints
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 400
Editorial — intuition, approach, complexity and pitfalls
Intuition
At each house you make a binary choice: rob it (then you could not have robbed the previous one) or skip it. The best total up to house i is max(skip = best up to i-1, rob = best up to i-2 + money[i]).
Approach
- Keep two rolling values: best up to the previous house and the house before that.
- For each house:
new = max(prev, prevPrev + money). - Roll forward; the last value is the answer.
Walkthrough
nums = [2, 7, 9, 3, 1]
cur: 2, 7, 11, 11, 12 -> answer 12 (2 + 9 + 1)Complexity
- Time — O(n): one pass.
- Space — O(1): two rolling variables instead of a DP array.
Common Pitfalls
- The choice is
max(cur, prev + x)-- skip this house, or rob it and add the best up to two houses back. Usingprevon both sides drops the skip option, and[1,2,3,1]returns 3 instead of 4. - The simultaneous assignment matters. Updating
prevbefore computing the newcurfeeds the new value back into its own formula, which quietly allows robbing adjacent houses.
Full Solution — all languages
class Solution:
def rob(self, nums):
prev, cur = 0, 0
for x in nums:
prev, cur = cur, max(cur, prev + x)
return curimport java.util.*;
class Solution {
public int rob(int[] nums) {
int prev = 0, cur = 0;
for (int x : nums) {
int t = Math.max(cur, prev + x);
prev = cur;
cur = t;
}
return cur;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int rob(vector<int>& nums) {
int prev = 0, cur = 0;
for (int x : nums) {
int t = max(cur, prev + x);
prev = cur;
cur = t;
}
return cur;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var rob = function(nums) {
let prev = 0, cur = 0;
for (const x of nums) {
const t = Math.max(cur, prev + x);
prev = cur;
cur = t;
}
return cur;
};