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

213. House Robber II

时间:2017-01-30 10:34:57      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:ever   one   min   without   attention   ems   represent   rem   rmi   

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.

此题和House Robber的不同在于,这个是首尾相连的,需要多考虑一步,当没选中第一个房子的时候可以选择最后一个房子,而当选中第一个房子的时候不可以选择最后一个房子。做法是把数组分成两个部分,然后求这两个部分最大值进行比较,代码如下:

public class Solution {

    public int rob(int[] nums) {

        if(nums.length==0) return 0;

        if(nums.length==1) return nums[0];

        if(nums.length==2) return Math.max(nums[0],nums[1]);

        if(nums.length==3) return Math.max(nums[0],Math.max(nums[1],nums[2]));

        return Math.max(helper(Arrays.copyOfRange(nums,0,nums.length-1)),helper(Arrays.copyOfRange(nums,1,nums.length)));

    }

    public int helper(int[] nums){

        int[] dp = new int[nums.length];

        dp[0] = nums[0];

        dp[1] = Math.max(nums[0],nums[1]);

        for(int i=2;i<nums.length;i++){

            dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);

        }

        return dp[nums.length-1];

    }

}

这个代码初始值要多判断很多步,下面来一个简练的:

public class Solution {

    public int rob(int[] nums) {

        if(nums.length==0) return 0;

        if(nums.length==1) return nums[0];

        return Math.max(helper(nums,0,nums.length-2),helper(nums,1,nums.length-1));

    }

    public int helper(int[] nums,int start,int end){

        int include = 0;

        int exclude = 0;

        for(int j=start;j<=end;j++){

            int i=include,e=exclude;

            include = e+nums[j];

            exclude = Math.max(i,e);

        }

        return Math.max(include,exclude);

    }

}

213. House Robber II

标签:ever   one   min   without   attention   ems   represent   rem   rmi   

原文地址:http://www.cnblogs.com/codeskiller/p/6357869.html

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