LeetCode 198: House Robber
思路
这题基本思路还是动态规划,对第i个房子如果不打劫其最大金额为max[i - 1];如果打劫,则第i - 1个房子不能打劫,最大金额为nums[i] + max[i - 2];
代码
public class Solution {
public int rob(int[] nums) {
int length = nums.length;
if (length == 0) return 0;
if (length == 1) return nums[0];
int[] max = new int[length];
max[0] = nums[0];
max[1] = nums[0] > nums[1] ? nums[0] : nums[1];
for (int i = 2; i < length; i++) {
//fetch the ith house, thus the i - 1th house can't be robbed
int tmp = nums[i] + max[i - 2];
//don't fetch the ith house, is just max[i - 1]
max[i] = tmp > max[i - 1] ? tmp : max[i - 1];
}
return max[length - 1];
}
}