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