[leedcode 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 arearranged 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) {
        //遍历两遍,第一遍包括头结点,不包括尾节点;第二遍包括尾节点,不包括头结点,求二者最大值
        if(nums.length==0) return 0;
        if(nums.length==1) return nums[0];//只有一个节点时,需特殊判断
        int unrob=0;
        int rob=0;
        for(int i=0;i<nums.length-1;i++){
            int temp=rob;
            rob=nums[i]+unrob;
            unrob=Math.max(unrob,temp);
        }
        int res1=Math.max(rob,unrob);
         unrob=0;
         rob=0;
        for(int i=1;i<nums.length;i++){
            int temp=rob;
            rob=nums[i]+unrob;
            unrob=Math.max(temp,unrob);
        }
        int res2=Math.max(rob,unrob);
        return Math.max(res1,res2);
    }
}

 

posted @ 2015-08-06 19:58  ~每天进步一点点~  阅读(125)  评论(0编辑  收藏  举报