198. House Robber

来源:互联网 发布:linux 重置网络配置 编辑:程序博客网 时间:2024/06/10 02:47

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);    }}

0 0
原创粉丝点击