题目:
分析:打家劫舍原问题可看这里,比原题多了一个环的条件。可以这么思考,如果首尾不相邻,那么就可以使用原问题的解法了,然后思考怎么做到首尾不相邻,可以分两种情况:1.考虑第一间房屋到倒数第二间房屋,2.考虑第二间房屋到最后一间房屋,这样首尾就不相邻了,可以使用原问题的解法了,同样是动态规划
注意一点: 如果只有一间房子,那么不需要分情况往下考虑了,直接偷
代码:
class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
if(nums.length == 1){
return nums[0];
}
//前一间房屋的偷窃最高金额
int before1 = 0;
//前两间房屋的偷窃最高金额
int before2 = 0;
int result1 = 0;
for(int i = 0; i < nums.length-1; i++){
int current_max = Math.max(before2 + nums[i], before1);
before2 = before1;
before1 = current_max;
}
result1 = before1;
before1 = before2 = 0;
for(int i = 1; i < nums.length; i++){
int current_max = Math.max(before2 + nums[i], before1);
before2 = before1;
before1 = current_max;
}
return Math.max(result1, before1);
}
}