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.
solution:
similar with house robber I, call that method twice, one not include first element, second not include last element.
if(nums.length ==1) return nums[0];
int take = 0;
int nontake = 0;
int maxprofit = 0;
for(int i=0;i<nums.length-1;i++){
take = nums[i] + nontake;
nontake = maxprofit;
maxprofit = Math.max(take, nontake);
}
take = 0;
nontake = 0;
int maxprofit1 = 0;
for(int i=1;i<nums.length;i++){
take = nums[i] + nontake;
nontake = maxprofit1;
maxprofit1 = Math.max(take, nontake);
}
return Math.max(maxprofit, maxprofit1);