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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 400
解题思路
本题可以采用动态规划来解决,我们用numsi表示第 i 户人家所拥有的钱数, dpi 表示该小偷在前 i 户人家,能够偷到的最大总钱数。假设当这个小偷来到第 i+1 户人家的门前时,已经知道了前面 dp0∼dpi 的取值,由于他不能连续偷相邻的两户人家,所以如果他偷了第 i+1 户人家,就不能偷第 i 户人家,那么他此时的总收入应该是 dpi−1+numsi+1 ,我们将这个数记为 t。如果 t>dpi ,那么 dpi+1=t ,如果 t≤dpi ,那么他还不如不偷第 i+1 户人家,维持在前 i 户人家得到的收入,也就是 dpi ,这种情况下, dpi+1=dpi 。所以, dpi+1 的取值取决于 t 和 dpi的大小,即: dpi+1=max{dpi,dpi−1+numsi+1} ,对这个式子做一下变形,可以得到 :
public int rob(int[] nums) {
int len = nums.length;
int[] dp = new int[len];
dp[0] = nums[0];
for (int i = 1; i < len; i++) {
if (i == 1) {
// 前两个数特殊处理
dp[i] = Math.max(dp[i-1], nums[i]);
} else {
dp[i] = Math.max(dp[i-1], nums[i] + dp[i - 2]);
}
}
return dp[len - 1];
}
public int rob(int[] nums) {
int len = nums.length;
int prePre = 0, pre = nums[0], current = nums[0];
for (int i = 1; i < len; i++) {
current = Math.max(pre, prePre + nums[i]);
prePre = pre;
pre = current;
}
return current;
}