leetcode 213. 打家劫舍 II

image

思路:因为第一个和最后一个不能同时选,所以将环形分成两段[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;
    }
}
posted @ 2022-03-24 21:35  livingsu  阅读(22)  评论(0)    收藏  举报