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.
只需要分情况讨论即可, 除去第一家或最后一家,将环断开。
这题又是一个状态的题,抢或不抢两种状态,分别开一个数组存
public class Solution {
public int rob(int[] nums) {
if(nums==null || nums.length==0) return 0;
if(nums.length==1) return nums[0];
int len = nums.length;
return Math.max(rob(nums, 0, len-2), rob(nums, 1, len-1));
}
public int rob(int[] nums, int start, int end){
int len = end-start+1;
int[] r = new int[len];
int[] s = new int[len];
int l = start;
r[0] = nums[l];
s[0] = 0;
for(int i =1; i< len; i++){
r[i] = Math.max(s[i-1]+nums[l+i], r[i-1]);
s[i] = Math.max(r[i-1], s[i-1]);
}
return Math.max(r[len-1], s[len-1]);
}
}