House Robber II
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #213
Like House Robber, but the houses are arranged in a circle, so the first and last houses are neighbors. Return the maximum amount you can rob without robbing two adjacent houses.
Examples
text
[2,3,2] → 3
[1,2,3,1] → 4
[1,2,3] → 3Hints
- The circle only adds one constraint: you can't take both house 0 and house n−1.
- So either house 0 is excluded or house n−1 is excluded. Solve the linear problem twice.
Approach
answer = max(linear(nums[1:]), linear(nums[:-1])), where linear is House Robber I: cur = max(prev + x, cur) with two rolling variables. Special case: n == 1 returns nums[0].
Breaking a cycle by case analysis on one element is a general trick for circular DP problems.
Complexity
Time: O(n). Space: O(1).
Python solution
def rob(nums):
def linear(arr):
prev = cur = 0
for x in arr:
prev, cur = cur, max(cur, prev + x)
return cur
if len(nums) == 1:
return nums[0]
return max(linear(nums[1:]), linear(nums[:-1]))JavaScript solution
function rob(nums) {
if (nums.length === 1) return nums[0];
const linear = (lo, hi) => {
let prev = 0, cur = 0;
for (let i = lo; i <= hi; i++) [prev, cur] = [cur, Math.max(cur, prev + nums[i])];
return cur;
};
return Math.max(linear(0, nums.length - 2), linear(1, nums.length - 1));
}