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 arearranged 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 tonightwithout alerting the police.
這道題和之前它的基礎版最大的不同就是所有house圍成了一個圈。之前我們只需要考慮這個house的前一個是否被rob與否。現在呢就有了特殊情況。
第一個和最后一個house不能同時被rob。
最為簡單的方法就是call兩次第一次的算法。(一個assume第一個house被rob,一個則assume最后一個house被rob。)
因為這里有nums.length-2,因此special case里面應該有nums.length==1的時候的單獨的算法。
代碼如下。~
public class Solution { public int rob(int[] nums) { if(nums.length==0||nums==null){ return 0; } return Math.max(rob1(nums,0,nums.length-2),rob1(nums,1,nums.length-1)); } private int rob1(int[]nums, int start,int end){ if(nums.length==0||nums==null){ return 0; } if(nums.length==1){ return nums[0]; } int prerob=0; int predontrob=0; for(int i=start;i<end+1;i++){ int curr=predontrob+nums[i]; int dontcurr=Math.max(prerob,predontrob); prerob=curr; predontrob=dontcurr; } return Math.max(prerob,predontrob); }}
新聞熱點
疑難解答