码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 213] House Robber II

时间:2015-08-06 21:40:39      阅读:143      评论:0      收藏: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 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);
    }
}

 

[leedcode 213] House Robber II

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4708998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!