https://leetcode.com/problems/house-robber-ii/
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
解题思路:
前面一题的follow-up,多了一个限制条件,第一个和最后一个房子,也算相邻,所以只能偷一个。这样在计算到dp[nums.length]的时候,不能再简单的max(dp[i - 2] + nums[i], dp[i - 1])了。前面的dp[i - 2]不能包含第一个房子。问题是,你不知道这个dp[i-2]是不是偷了第一个房子,因为子状态的定义是,偷到第i个房子时候的最大值。
所以,这题可以分解为两个问题,1)偷第一个房子,时候的最大值,2)偷最后一个房子,时候的最大值。
dp两次,再求最大值。
public class Solution {
public int rob(int[] nums) {
if(nums.length == 0) {
return 0;
}
if(nums.length == 1) {
return nums[0];
}
int prepre = 0;
int pre = 0;
int result = pre;
int max1 = 0;
for(int i = 0; i < nums.length - 1; i++) {
result = Math.max(pre, prepre + nums[i]);
prepre = pre;
pre = result;
}
max1 = result; int max2 = 0;
prepre = 0;
pre = 0;
result = pre; for(int i = 1; i < nums.length; i++) {
result = Math.max(pre, prepre + nums[i]);
prepre = pre;
pre = result;
}
max2 = result;
return Math.max(max1, max2);
}
}