"Simple Algorithm" 36. Dagujieshe

Source: Internet
Author: User

Topic:

you are a professional thief, planning to steal houses along the street. Each room has a certain amount of cash, the only factor that affects your theft is that adjacent houses are equipped with interconnected anti-theft systems, and if two adjacent houses are hacked by thieves at the same night, the system will automatically alarm you. Given a non-negative integer array representing the amount of each house deposit, calculate the maximum amount you can steal without touching the alarm device. Example1: Enter: [1,2,3,1] Output:4Explanation: Stealing1Number of houses (amount =1), and then steal3Number of houses (amount =3). The maximum amount of theft=1+3=4. Example2: Enter: [2,7,9,3,1] Output: AExplanation: Stealing1Number of houses (amount =2), stealing3Number of houses (amount =9), and then steal5Number of houses (amount =1). The maximum amount of theft= =2+9+1= A。

Problem Solving Ideas:

Simple, dynamic planning can be achieved. Cannot allow adjacent houses to be robbed at the same time. If a room is robbed, the i-1 room cannot be robbed and the maximum amount of robbery in the pre-I room is dp[i].

So get the recursive formula:

Dp[i] = max (Dp[i-1],dp[i-2] + nums[i]);

The code is as follows:

classSolution { Public:    intRob (vector<int>&nums) {Vector<int> dp (nums.size (),0); intLen =nums.size (); if(Len <=0){            return 0; }                if(len = =1){            returnnums[0]; }                if(len = =2){            returnMax (nums[0],nums[1]); } dp[0] = nums[0]; dp[1] = max (nums[0],nums[1]);  for(inti =2; i < Len; ++i) {Dp[i]= Max (dp[i-1],dp[i-2]+Nums[i]); }                returndp[len-1]; }};

"Simple Algorithm" 36. Dagujieshe

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.