題目描述
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.
題目本質(zhì):在House Robber I的基礎(chǔ)上猿妈,增加一個(gè)考慮:不能同時(shí)搶劫第一個(gè)和最后一個(gè)house怪蔑。因此审洞,可以分別去掉頭尾的house,然后在子數(shù)組中用I中的方法找到最大和雄卷,從頭尾的兩個(gè)最大和中再選較大的那個(gè)作為最終的輸出。
public class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int len = nums.length;
if(len == 1)
return nums[0];
if(len == 2)
return Math.max(nums[0], nums[1]);
return Math.max(sub_rob(nums,0,len-2), sub_rob(nums,1,len-1));
}
public int sub_rob(int[] nums, int start, int end){
int len = end - start + 1;
int temp0 = 0, temp1 = nums[start];
int temp = 0;
for(int i = 1; i < len; i++){
temp = Math.max(temp0, temp1);
temp1 = temp0 + nums[start+i];
temp0 = temp;
}
return Math.max(temp0, temp1);
}
}