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