House Robber II

Houses arranged in a circle — run linear House Robber on two ranges, exclude either head or tail.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
dp

Problem#

Same as House Robber but houses are arranged in a circle — house 0 is adjacent to house n-1.

Examples#

  • [2,3,2]3
  • [1,2,3,1]4

Constraints#

  • 1 <= n <= 100.

Approach#

Run the linear DP twice: once on nums[0..n-2] (exclude last), once on nums[1..n-1] (exclude first). Return the max.

Solution#

House Robber II
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 1) return nums[0];
return max(robLinear(nums, 0, nums.size() - 2),
robLinear(nums, 1, nums.size() - 1));
}
private:
int robLinear(vector<int>& nums, int lo, int hi) {
int prev = 0, curr = 0;
for (int i = lo; i <= hi; ++i) {
int next = max(curr, prev + nums[i]);
prev = curr;
curr = next;
}
return curr;
}
};

Editorial#

The circular constraint reduces to two non-circular cases: either the first house is robbed (then the last can’t be) or the first isn’t (the last is free game). Linear House Robber over each window covers both.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.