# [leetcode] House Robber II

### House Robber II

Note: This is an extension of House Robber.

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

It’s a very similar question to House Robber I, except the houses are circled. The first house and the last house are considered as adjacent.

Find a start point, say nums. Consider two situations, rob it or not. Discuss them separately, and find the maximum result.

```//Just decide to rob the first room or not,
//divide it into two situations.

class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() == 0) return 0;
if(nums.size() == 1) return nums;
if(nums.size() == 2) return max(nums, nums);
//n == 3?

//case 1 rob nums
int dp[nums.size()];
memset(dp, 0, sizeof(dp));
dp = nums;
dp = 0;
for(size_t  i = 2; i < nums.size(); i++){
for(size_t j = 0; j < i - 1; j++){
int value = nums[i] + dp[j];
if(dp[i] < value){
dp[i] = value;
}
}
}
int ans1 = max(dp[nums.size() - 2], dp[nums.size() - 3]); // do not rob the last house
memset(dp, 0, sizeof(dp));
dp = 0;
dp = nums;
for(size_t  i = 2; i < nums.size(); i++){
for(size_t j = 0; j < i - 1; j++){
int value = nums[i] + dp[j];
if(dp[i] < value){
dp[i] = value;
}
}
}
int ans2 = max(dp[nums.size() - 1], dp[nums.size() - 2]);
return max(ans1, ans2);
}
};```

Again, walk through is very important. This site uses Akismet to reduce spam. Learn how your comment data is processed.