leetcode 213. 打家劫舍 II

思路:因为第一个和最后一个不能同时选,所以将环形分成两段[0,len-2]和[1,len-1],分别用"打家劫舍1"求解,然后求最大值即可。
class Solution {
public int rob(int[] nums) {
int len=nums.length;
if(len==1) return nums[0];
return Math.max(rob(nums,0,len-2),rob(nums,1,len-1));
}
private int rob(int[] nums,int low, int high){
int len=high-low+1;
if(len==1) return nums[low];
int first=nums[low],second=Math.max(nums[low],nums[low+1]);
for(int i=2;i<len;i++){
int cur=Math.max(second,first+nums[low+i]);
first=second;
second=cur;
}
return second;
}
}

浙公网安备 33010602011771号