Problem Description :
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
For the House Robber, we can use simple a dp method to solve the problem.
int rob(vector<int>& nums)
{
int n = nums.size();
int a = 0, b = 0, money = 0;
for (int i = 0; i < n; ++i)
{
money = max(a + nums[i], b);
a = b;
b = money;
}
return money;
}
python code :
def rob(self, nums):
last, now = 0, 0
for i in nums:
#last, now = now, max(last + i, now)
now, last = max(last + i, now), now
return now
For the follow up question :
The problem can simply be decomposed into two House Robber problems. Suppose there are n houses, we could split the way that rob the house
1. rob houses from 0 to n - 2;
2. rob houses from 1 to n - 1;
class Solution {
private :
int rob(vector<int> &nums, int l, int r)
{
int pre = 0, cur = 0;
for (int i = l; i <= r; i++)
{
int money = max(pre + nums[i], cur);
pre = cur;
cur = money;
}
return cur;
}
public :
int rob(vector<int>& nums) {
int n = nums.size();
if (n < 2) return n ? nums[0] : 0;
return max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
}
};