Dynamic Programming——No.213 House Robber II

Problem:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

Explanation:

你要去抢劫,但是不能在一个晚上抢紧邻的两家,且所有的家构成环,即抢了第一家就不能抢最后一家,找出能抢到最多钱的方案。

My Thinking:

My Solution:

Optimum Thinking:

第一家和最后一家只能抢其中的一家,如果我们把第一家和最后一家分别去掉,各算一遍能抢的最大值,然后比较两个值取其中较大的一个即为所求。

Optimum Solution:

 (1)

class Solution {
    public int rob(int[] nums) {
        if(nums.length==0)
            return 0;
        if(nums.length==1)
            return nums[0];
        int maxexceptfirst=rob(nums,1,nums.length-1);
        int maxexceptlast=rob(nums,0,nums.length-2);
        return Math.max(maxexceptfirst,maxexceptlast);
    }
    public int rob(int[] nums,int left,int right){
        if(right-left<=1)
            return nums[left];
        int[] dp=new int[right-left+1];
        dp[0]=nums[left];
        dp[1]=Math.max(nums[left+1],nums[left]);
        for(int i=2;i<right-left+1;i++){
            dp[i]=Math.max(dp[i-1],nums[i+left]+dp[i-2]);
        }
     
        return dp[right-left];
    }
}

(2)

class Solution {
    public int rob(int[] nums) {
        if(nums.length==0)
            return 0;
        if(nums.length==1)
            return nums[0];
        int maxexceptfirst=rob(nums,1,nums.length-1);
        int maxexceptlast=rob(nums,0,nums.length-2);
        return Math.max(maxexceptfirst,maxexceptlast);
    }
    private int rob(int[] num, int left, int right) {
        int include = 0, exclude = 0;
        for (int j = left; j <= right; j++) {
            int i = include, e = exclude;
            include = e + num[j];
            exclude = Math.max(e, i);
        }
        return Math.max(include, exclude);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值