[Leetcode] House robber

Source: Internet
Author: User

House robber

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.

Ideas:

Dynamic planning, Dp[i] represents the maximum benefit to the house I, there are two cases, or the House can not be robbed, because the previous one has been visited, and the other is that the house can be robbed, so the maximum benefit of the two before the return of the building. In mathematical expression: dp[i] = max (num[i]+dp[i-2], dp[i-1]

Exercises

classSolution { Public:    intRob (vector<int> &num) {        intn=num.size (); if(n==0)            return 0; if(n==1)            returnnum[0]; if(n==1)            returnMax (num[0], num[1]); int*DP =New int[n]; dp[0] = num[0]; dp[1] = max (num[0], num[1]);  for(intI=2; i<n;i++) {Dp[i]= Max (num[i]+dp[i-2], dp[i-1]); }        returndp[n-1]; }};
View Code

Something:

The above method space complexity of 0 (n), in fact, can also be optimized to O (1), which is similar to the topic of another DP climbing stairs

classSolution { Public:    intRob (vector<int> &num) {        intn=num.size (); if(n==0)            return 0; if(n==1)            returnnum[0]; if(n==2)            returnMax (num[0], num[1]); intPre2 = num[0]; intPre1 = Max (num[0], num[1]); intcur;  for(intI=2; i<n;i++) {cur= Max (pre2+Num[i], pre1); Pre2=Pre1; Pre1=cur; }        returncur; }};
View Code

[Leetcode] 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.