198,house robber

Source: Internet
Author: User

First, the topic

You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were broken Into on the same night.

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.

Second, analysis

A simple dynamic plan.

F (k): The maximum amount of money to be obtained when robbing a room K

The following recurrence relationship is available:

F (0) = nums[0]f (1) = max (num[0], num[1= max (f (k 2) + nums[k], f (k1))

Third, the Code

1) More easy to understand, the interpretation of the above three formula

1 classSolution {2  Public:3     intRob (vector<int>&nums) {4         intLength =nums.size ();5         if(Length = =0)6             return 0;7vector<int> Money (length, nums[0]);8         if(Length = =1)9             returnnums[0];Ten         Else { Onemoney[1] = max (nums[0], nums[1]); A              for(inti =2; i < length; ++i) { -Money[i] = max (money[i-1], money[i-2] +nums[i]); -             } the         } -         returnMoney[length-1]; -  -     } +};

2) optimization of the above program

1 classSolution {2  Public:3     intRob (vector<int>&nums) { 4         intn = nums.size (), pre =0, cur =0;5          for(inti =0; I < n; i++) {6             intTEMP = max (pre +nums[i], cur);7Pre =cur;8Cur =temp;9         }Ten         returncur; One     } A};

3) Python implementation

1 class Solution: 2     3     def Rob (Self, nums): 4         5         Last, today = 0, 06         7for in          nums:last, now = Now, Max ( Last + I, now)8                 9         return now

 

198,house robber

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.