LeetCode 198. House Robber

198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that 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.


题目大意:

   我们扮作强盗去房间里抢劫,抢劫的时候不能连续抢挨在一起的房间,给出每个房间里由的钱数,求我们在遵守规则的情况下所能盗走的最大金钱。


 思路:

   1.子问题划分
      设m[i] i=1...len 是保存 抢劫前i个房间所获得的最大金钱数量。由题意我可知,若想保证抢劫前len个房间所获金额最大,则抢劫前i个房间时
    所获金额一定也是当前1..i段中最大的。
   
    2.递推方程
       初值: m[0]=nums[0],
                m[1]=max{m[0],nums[1]}   即抢劫前两个房间所获的金钱 只取其中较大者
       方程:   m[i]=Max{m[i-2]+nums[i],m[i-1]}  ,  len>i>1
m[i-2]+nums[i]即代表抢劫第i个房间,不抢第i-1个反击,此时的获得的金钱数是就是抢劫前i-2个房间的金钱数假设第i个房间的金钱
m[i-1]即代表不抢第i个房间,此时的m[i]等于之前计算出的抢劫前i-1个房间所得金额
        

      3.输出
最后输出即决定是不是要抢最后一个房间,若抢则输出m[len-1],若不抢则输出m[len-2]  (抢不抢由其大小决定)



代码:

   public int rob(int[] nums) {
    	int len = nums.length;
    	if(len == 0)
    		return 0;
    	if(len == 1)
    		return nums[0];
    	int m[] = new int[len];
    	m[0] = nums[0];
    	m[1] = Math.max(nums[1],m[0]);
    	for(int i=2;i<len;i++){
    		m[i] = Math.max(m[i-2]+nums[i],m[i-1]);
    	}
    	return Math.max(m[len-2], m[len-1]);
    }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值