美文网首页
213. House Robber II

213. House Robber II

作者: HalcyonMoon | 来源:发表于2016-06-29 16:23 被阅读0次

    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]);
        }
    }
    

    相关文章

      网友评论

          本文标题:213. House Robber II

          本文链接:https://www.haomeiwen.com/subject/ymrxjttx.html