题意:
给定一个非负整数的数组代表每个房屋里的金额,确定今晚在不偷相邻的两个房屋能抢到的最大金额。最后一个房屋和第一个房屋相邻
分析:
r如果没有最后一个房屋和第一个房屋相邻的条件,我们知道,前n间房间的最大利润就是:前n-2间的最大利润加上第n间的利润 和 前n-1间的利润的大者。
现在因为限制了条件,就必须要分类讨论了,我们用两个动态方程分类讨论,一个是拿第一间,一个是拿第二间。但是当拿第一间的时候,最后只能拿到倒数第二间,不能拿最后一间。
public class Solution {
public int rob(int[] nums) {
if (nums.length == 0)
return 0;
if (nums.length == 1)
return nums[0];
int[] first = new int[nums.length];
int[] second = new int[nums.length];
first[0] = nums[0];
first[1] = nums[0];
second[0] = 0;
second[1] = nums[1];
for (int i = 2; i < nums.length; i++) {
first[i] = Math.max(first[i-1], first[i-2] + nums[i]);
second[i] = Math.max(second[i-1], second[i-2] + nums[i]);
}
return Math.max(first[nums.length-2], second[nums.length-1]);
}
}