House Robber II
Pattern: 1D DP
The houses are in a circle, so the first and last are neighbours and at most one of them is robbed. Solve the straight-street problem twice: without the last house and without the first, and take the better answer.
The problem
Like House Robber, but the houses stand in a circle. [2, 3, 2] gives 3; [1, 2, 3, 1] gives 4.
Think first
- Which pair of houses is new as neighbours?
- Can both be robbed?
- How do you reuse House Robber?
Hints
Brute force, and why it fails
Try every valid set around the circle: exponential.
The key insight
Dropping one end breaks the circle into a line, and one of the two lines contains the best answer.
Dry run
| a | 3 |
|---|
nums [2, 3, 2]. Without the last: [2, 3] gives 3.
Step 1 of 3
The plan
if n == 1: nums[0]
return max(line(nums[0..n-2]), line(nums[1..n-1]))
Complexity
- Time
O(n)- Space
O(1)
Two linear passes.
Edge cases
- One house: rob it.
- Two houses: the larger.
- Three equal houses.
I've built my logic, show the code
Java
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if (n == 1) return nums[0];
return Math.max(line(nums, 0, n - 2), line(nums, 1, n - 1)); // the first and last are neighbours: drop one of them
}
private int line(int[] a, int lo, int hi) { // House Robber on a[lo..hi]
int take = 0, skip = 0;
for (int i = lo; i <= hi; i++) {
int newTake = skip + a[i];
skip = Math.max(take, skip);
take = newTake;
}
return Math.max(take, skip);
}
}C++
class Solution {
public:
int rob(vector<int>& nums) {
int n = static_cast<int>(nums.size());
if (n == 1) return nums[0];
return max(line(nums, 0, n - 2), line(nums, 1, n - 1)); // the first and last are neighbours: drop one of them
}
int line(vector<int>& a, int lo, int hi) { // House Robber on a[lo..hi]
int take = 0, skip = 0;
for (int i = lo; i <= hi; i++) {
int newTake = skip + a[i];
skip = max(take, skip);
take = newTake;
}
return max(take, skip);
}
};Python
class Solution:
def rob(self, nums: list[int]) -> int:
def line(a): # House Robber on a straight street
take = skip = 0
for x in a:
take, skip = skip + x, max(take, skip)
return max(take, skip)
if len(nums) == 1:
return nums[0]
return max(line(nums[:-1]), line(nums[1:])) # the first and last are neighbours: drop one of themCommon mistakes
- Forgetting the one-house case.
- Running the line version on the whole circle.