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.

public class Solution {
    public int rob(int[] nums) {
        int len = nums.length;
        if(len == 0){
            return 0;
        }else if(len == 1){
            return nums[0];
        }
        
        int rob[] = new int[len];
        int rob2[] = new int[len];
        
        rob[0] = nums[0];
        rob2[0] = 0;
        
        rob[1] = Math.max(nums[0], nums[1]);
        rob2[1] = nums[1];
        
        for(int i = 2; i< len; i++){
            if(i<len-1){
                rob[i] = Math.max(rob[i-2] + nums[i], rob[i-1]);
            }else{
                rob[i] = rob[i-1];
            }
            rob2[i] = Math.max(rob2[i-2] + nums[i], rob2[i-1]);
        }
        return Math.max(rob[len-1], rob2[len-1]);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容