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.
題目
在上次打劫完一條街道之后朋腋,竊賊又發(fā)現(xiàn)了一個(gè)新的可以打劫的地方但校,但這次所有的房子圍成了一個(gè)圈前翎,這就意味著第一間房子和最后一間房子是挨著的于购。每個(gè)房子都存放著特定金額的錢。你面臨的唯一約束條件是:相鄰的房子裝著相互聯(lián)系的防盜系統(tǒng)毡鉴,且 當(dāng)相鄰的兩個(gè)房子同一天被打劫時(shí)闺骚,該系統(tǒng)會(huì)自動(dòng)報(bào)警航唆。
給定一個(gè)非負(fù)整數(shù)列表将谊,表示每個(gè)房子中存放的錢冷溶, 算一算渐白,如果今晚去打劫尊浓,你最多可以得到多少錢 在不觸動(dòng)報(bào)警裝置的情況下。
注意事項(xiàng)
這題是House Robber的擴(kuò)展纯衍,只不過是由直線變成了圈
樣例
給出nums = [3,6,4], 返回 6栋齿, 你不能打劫3和4所在的房間,因?yàn)樗鼈儑梢粋€(gè)圈襟诸,是相鄰的.
分析
打劫房屋問題的擴(kuò)展瓦堵,要求首尾不能相連,那就調(diào)用上一題中的方法兩次歌亲,第一次不包括尾菇用,第二次不包括首,最后求出最大就可以了
代碼
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);
}
}