Skip to main content

213. House Robber II

class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();

if (n == 0) return 0;
if (n == 1) return nums[0];

int max1 = helper(nums, 0, n - 1);
int max2 = helper(nums, 1, n);

return max(max1, max2);
}
int helper(vector<int>& nums, int left, int right) {
int rob = 0, notRob = 0;
for (int i = left; i < right; ++i) {
int temp = rob;
rob = max(nums[i] + notRob, rob);
notRob = temp;
}
return rob;
}
};
  • T: O(N)O(N)
  • S: O(1)O(1)