Note:this is a extension of house robber.
After robbing those houses on that street, the thief have found himself a new place for his thievery so that he would not GE T too much attention. This time, all houses at the is arranged in a circle. That's means the first house was 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 in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
The improvement on the previous topic, that is, the first is connected, and then find the biggest robbery money.
method is based on the previous method, if the last
per + nums[i] > Curr && nums[0] + nums[2] > nums[1]
Judge for a moment. Second, it is divided into two arrays to judge.
Public classSolution { Public intRobint[] nums) { if(Nums.length = = 0){ return0; } if(Nums.length = = 1){ returnNums[0]; } int[] Nums2 =New int[Nums.length]; for(inti = 0; i < nums.length-1; i++) {Nums2[i]= nums[i + 1]; } nums2[nums.length-1] = Nums[0]; returnMath.max (Robber (nums), Robber (NUMS2)); } Public intRobber (int[] nums) { intper = Nums[0]; intCurr = nums[1]; for(inti = 2; i < nums.length; i++){ intnum = Math.max (Curr, per +Nums[i]); if(i = = Nums.length-1){ if(per + nums[i] > Curr && nums[0] + nums[2] > nums[1]){ returnMath.max (Math.max (Nums[0], nums[i]) + per-nums[0], Curr); }} per=Curr; Curr=num; } returnCurr; }}
can be slightly optimized.
Public classSolution { Public intRobint[] nums) { if(Nums.length = = 0){ return0; } if(Nums.length = = 1){ returnNums[0]; } returnMath.max (Robber (nums, 0, nums.length-1), Robber (nums, 1, nums.length)); } Public intRobber (int[] Nums,intStartintend) { intper = 0, Curr = 0; for(inti = start; I < end; i++){ intnum = Math.max (Curr, per +Nums[i]); Per=Curr; Curr=num; } returnCurr; }}
Leetcode 213. House Robber II Robbing Houses II----------Java