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.
Credits:Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
題目
在上次打劫完一條街道之后,竊賊又發現了一個新的可以打劫的地方,但這次所有的房子圍成了一個圈,這就意味著第一間房子和最后一間房子是挨著的。每個房子都存放著特定金額的錢。你面臨的唯一約束條件是:相鄰的房子裝著相互聯系的防盜系統,且 當相鄰的兩個房子同一天被打劫時,該系統會自動報警。
給定一個非負整數列表,表示每個房子中存放的錢, 算一算,如果今晚去打劫,你最多可以得到多少錢 在不觸動報警裝置的情況下。
注意事項
這題是House Robber的擴展,只不過是由直線變成了圈
樣例
給出nums = [3,6,4], 返回 6, 你不能打劫3和4所在的房間,因為它們圍成一個圈,是相鄰的.
分析
打劫房屋問題的擴展,要求首尾不能相連,那就調用上一題中的方法兩次,第一次不包括尾,第二次不包括首,最后求出最大就可以了
代碼
public class Solution {
public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
return Math.max(robber1(nums, 0, nums.length - 2), robber1(nums, 1, nums.length - 1));
}
public int robber1(int[] nums, int start, int end) {
if(start == end)
return nums[start];
if(end == start+1)
return Math.max(nums[start], nums[start+1]);
int[] dp = new int[end-start+2];
dp[start] = nums[start];
dp[start+1] = Math.max(nums[start], nums[start+1]);
for(int i=start+2;i<=end;i++)
dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i]);
return dp[end];
}
}
方法二
public class Solution {
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
}
private int rob(int[] num, int lo, int hi) {
int include = 0, exclude = 0;
for (int j = lo; j <= hi; j++) {
int i = include, e = exclude;
include = e + num[j];
exclude = Math.max(e, i);
}
return Math.max(include, exclude);
}
}