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.
题目的意思是说数组代表这条街上各个房子中的钱,不能拿相邻房子的钱,问最大能获得的钱是多少?
假设有一个这样的数组:
index: 0 1 2 3 4 5 6 7
value: 4 6 9 7 4 5 7 2
我们新开一个数组cache,cache[ i ] 代表 从0 到 i index 这些房子中所能获得的最多的钱。
假设此时index = 7, 如果我们取了index = 7 的房子的钱nums [ 7 ] ,那么前面的房子的钱只能取cache[5]。(因为不能取相邻的)
如果我们不取index = 7的房子的钱,我们可以取cache[6] 的钱。
所以,我们得到一个计算的公式,cache[ i ] = max( nums[ i ] + cache[ i - 2], cache[ i - 1] )。
同时不要忘了cache的base条件为:cache[ 0 ] = nums[ 0 ] , cache[ 1 ] = max ( nums[ 0 ], nums[ 1 ] )
代码:
public class HouseRobber {
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
if (n == 2) {
return Math.max(nums[0], nums[1]);
}
int[] cache = new int[nums.length];
for (int i = 0; i <cache.length; i++) {
cache[i] = -1;
}
cache[0] = nums[0];
cache[1] = Math.max(nums[0], nums[1]);
return doRob(nums, cache, nums.length - 1);
}
private int doRob(int[] nums, int[] cache, int i) {
int twoBeforeI = cache[i - 2] == -1 ? doRob(nums, cache, i - 2) : cache[i - 2];
int oneBeforI = cache[i - 1] == -1 ? doRob(nums, cache, i - 1) : cache[i - 1];
cache[i] = Math.max(twoBeforeI + nums[i], oneBeforI);
return cache[i];
}
}