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.
publicintrob(int[] nums) {if (nums ==null||nums.length==0) {return0; } elseif (nums.length==1) {return nums[0]; }int n =nums.length;int max1 =helper(nums,0, n -2);int max2 =helper(nums,1, n -1);returnMath.max(max1, max2);}privateinthelper(int[] nums,int s,int e) {if (s == e) {return nums[s]; }int n =nums.length;int[] dp =newint[n]; dp[s] = nums[s]; dp[s +1] =Math.max(nums[s], nums[s +1]);for (int i = s +2; i <= e; i++) { dp[i] =Math.max(dp[i -2] + nums[i], dp[i -1]); }return dp[e];}
publicinthouseRobber2(int[] nums) {if (nums ==null||nums.length==0) {return0; } elseif (nums.length==1) {return nums[0]; }int n =nums.length;int rob0ToSencondLast =robHouseRange(nums,0, n -2);int rob1ToLast =robHouseRange(nums,1, n -1);returnMath.max(rob0ToSencondLast, rob1ToLast);}privateintrobHouseRange(int[] nums,int s,int e) {int[] dp =newint[e +1]; // make it as long as the original array - 1// need to assign dp according to start index,// or it will be hard to control since one starts from 1 the other starts from 0 dp[s] = nums[s]; dp[s +1] =Math.max(nums[s], nums[s +1]);for (int i = s +2; i <= e; i++) { dp[i] =Math.max(nums[i] + dp[i -2], dp[i -1]); }return dp[e];}