House Robber
Pattern: 1D DP
You cannot rob two neighbouring houses. For each house, keep the best total if this house is robbed and if it is not: robbing it adds its money to the best that skipped the previous one.
The problem
Each house has some money; robbing two neighbouring houses sets off an alarm. Return the most money you can take. [1, 2, 3, 1] gives 4; [2, 7, 9, 3, 1] gives 12.
Think first
- If you rob house i, which house must you skip?
- What two numbers are enough to carry along?
- What is the answer at the end?
Hints
Brute force, and why it fails
Try every set of houses with no two neighbours: exponential.
The key insight
Whether the previous house was robbed is the only thing that matters about the past.
Dry run
| take | 2 |
|---|---|
| skip | 0 |
nums [2, 7, 9, 3, 1]. After 2: take 2, skip 0.
Step 1 of 3
The plan
take = skip = 0
for x: take, skip = skip + x, max(take, skip)
return max(take, skip)
Complexity
- Time
O(n)- Space
O(1)
One pass.
Edge cases
- One house.
- Two houses: the larger.
- All zeros.
I've built my logic, show the code
Java
class Solution {
public int rob(int[] nums) {
int take = 0, skip = 0; // best so far if the last house was robbed / not robbed
for (int x : nums) {
int newTake = skip + x; // robbing this house needs the previous one left alone
skip = Math.max(take, skip);
take = newTake;
}
return Math.max(take, skip);
}
}C++
class Solution {
public:
int rob(vector<int>& nums) {
int take = 0, skip = 0; // best so far if the last house was robbed / not robbed
for (int x : nums) {
int newTake = skip + x; // robbing this house needs the previous one left alone
skip = max(take, skip);
take = newTake;
}
return max(take, skip);
}
};Python
class Solution:
def rob(self, nums: list[int]) -> int:
take = skip = 0 # best so far if the last house was robbed / not robbed
for x in nums:
take, skip = skip + x, max(take, skip) # robbing this house needs the previous one left alone
return max(take, skip)Common mistakes
- Robbing every other house blindly.
- Updating skip with the new take.