House robber II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.