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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

对于每一个房子能不能抢,取决于前一个房子有没有抢过。首先假设我们不抢这个房子,那么最大收益是前一个房子抢或者没被抢的最大值,如果抢这个房子,就是不抢前一个房子的最大值加上这个房子的金额。步骤如下:

1、把之前的currentNo, 和 currentRob都变成preNo,preRob。

2、如果这间房子不抢,currentNo是preNo,preRob较大的一个。

3、如果抢这间房子,currentRob是preNo加上这间房子的金额。

代码如下:

public class Solution {
    public int rob(int[] nums) {
        int currRob = 0, currNo = 0;
        for (int num:nums) {
            int preNo = currNo;
            int preRob = currRob;
            currNo = Math.max(preNo, preRob);
            currRob = preNo + num;
        }
        return Math.max(currNo, currRob);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值