213. 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.

一刷
题解:
两个元素的dp

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        return Math.max(rob(nums, 0, nums.length-2), rob(nums, 1, nums.length-1));
    }
    
    private int rob(int[] nums, int lo, int hi){
        if(nums == null || lo>hi) return 0;
        //robLast, take into account the i-1, notRob, not take into account i-1
        int robLast = 0, notRobLast = 0, res = 0;
        for(int i=lo; i<=hi; i++){
            res = Math.max(robLast, notRobLast+nums[i]);
            notRobLast = robLast;
            robLast = res;
        }
        return res;
    }
}

二刷
dynamic programming

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length ==1) return nums[0];
       return Math.max(rob(0, nums.length-2, nums), rob(1, nums.length-1, nums)); 
    }
    
    private int rob(int lo, int hi, int[] nums){
        int rob = 0, notRob = 0;
        for(int i=lo; i<=hi; i++){
            int notRob_ori = notRob;
            notRob = rob;
            rob = Math.max(notRob_ori + nums[i], rob);
        }
        return Math.max(rob, notRob);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容