213. House Robber II

2016-06-29  本文已影响0人  HalcyonMoon

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]);
    }
}
上一篇下一篇

猜你喜欢

热点阅读