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 problem is House robber's follow up, added to the ring considerations. In fact, the limit is that if we take the head of the array, there must be no way to take the tail element of the array, if you take the tail, there must be no way to take the head element of the array. That is, we do not necessarily take the maximum Rob result for all arrays. It is either taking NUMS[1...N] or nums[0...n-1]. Finally, the maximum value of two results, combined with House robber's first question, you can get the solution of the problem, the time complexity of O (n), the space Complexity of O (1), the code is as follows:
classsolution (object):defRob (Self, nums):""": Type Nums:list[int]: Rtype:int""" #1.first pop out the leftest element #2.next pop out the rightest elemnt #3.get the max value of them. if notNums:return0ifLen (Nums) < 3: returnMax (nums)#First pop out the leftest elementF1 = nums[1] F2= Max (f1,nums[2]) forNinchNums[3:]: Res= max (F1 +N, F2) F1=F2 F2=Res res1=F2 F1=Nums[0] F2= Max (f1,nums[1]) forNinchNums[2:-1]: Res= max (F1 +N, F2) F1=F2 F2=Res res2=F2returnMax (Res1, Res2)
House robber II