题目
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.
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.
算法
一个经典的dp问题(Maximum Independent Set),使用dp数组,dp[i]记录0到i个数据中可满足条件的最大值,递推式
d
p
[
i
]
=
m
a
x
(
d
p
[
i
−
1
]
,
d
p
[
i
−
2
]
+
n
u
m
s
[
i
]
)
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
dp[i]=max(dp[i−1],dp[i−2]+nums[i])
其中第一项是不包含元素nums[i]的最大值,第二项是包含。
由于递推时只用到前两次的数据,所以只需要记录两个变量不需要整个数组。
代码
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) {
return nums[0];
}
int v1 = nums[0];
int v2 = Math.max(nums[0], nums[1]);
int index = 2;
int temp;
while (index < nums.length) {
temp = Math.max(v1 + nums[index++], v2);
v1 = v2;
v2 = temp;
}
return v2;
}
写完了看了下参考解答,发现有一种不需要处理特殊情况的写法,非常巧妙。
提前把v1,v2设置成0,第一个数后v2是第一个数,v1是0,正确;第二个数后v2是前两个数中较大的,v1是第一个数,正确。
public int rob(int[] nums) {
int prevToPrev = 0, prev = 0, maxSoFar = 0;
for (int n : nums) {
maxSoFar = Math.max(prev, prevToPrev + n);
prevToPrev = prev;
prev = maxSoFar;
}
return maxSoFar;
}