House Robber
Medium · Dynamic programming
Jump to codeEach house along a street contains a nonnegative amount. Find the maximum total obtainable without choosing two neighboring houses. Choosing none is allowed.
Examples
Example 1
nums = [1,2,3,1]
Output: 4
Example 2
nums = [2,7,9,3,1]
Output: 12
Constraints
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 100
Need a hint?
At each house, choose between skipping it and combining it with the best earlier non-neighboring total.
Asked in real interviews
Candidates reported versions of House Robber from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Track the best total through the previous house and through the house before that. For value x, compute max(previous, beforePrevious + x), then shift the two states. Initialize both to zero.
Complexity
O(n) time and O(1) space.
Python reference solution
def rob(nums):
before = current = 0
for value in nums:
before, current = current, max(current, before + value)
return current
JavaScript solution
function rob(nums) {
let before = 0, current = 0;
for (const value of nums) [before, current] = [current, Math.max(current, before + value)];
return current;
}
Java solution
import java.util.*;
class Solution {
public int rob(int[] nums) {
int before = 0, current = 0;
for (int value : nums) {
int next = Math.max(current, before + value);
before = current; current = next;
}
return current;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int rob(vector<int> &nums) {
int before = 0, current = 0;
for (int value : nums) {
int next = max(current, before + value);
before = current; current = next;
}
return current;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
3,
1
]
]4
[
[
2,
7,
9,
3,
1
]
]12
[
[
1
]
]1
[
[
2,
1,
1,
2
]
]4
[
[
2,
4,
8,
9,
9,
3
]
]19
Drafts are saved per language in this browser when storage is available.