[Simple Algorithm] 36. Robbery

topic:

You are a professional thief planning to steal houses along the street. There is a certain amount of cash hidden in each room. The only constraint that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by thieves at the same night, the system will automatically alarm .

Given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal without triggering the alarm.

Example 1 :

Input: [ 1 , 2 , 3 , 1 ]
Output: 4 
Explanation: Steal house 1 (amount = 1 ), then steal house 3 (amount = 3 ).
     Maximum amount stolen = 1 + 3 = 4 .
Example 2 :

Input: [ 2 , 7 , 9 , 3 , 1 ]
Output: 12 
Explanation: Steal house 1 (amount = 2 ), steal house 3 (amount = 9 ), then steal house 5 (amount = 1 ).
     Maximum amount stolen = = 2 + 9 + 1 = 12 .

Problem solving ideas:

This problem is simple and can be implemented by dynamic programming. Since adjacent houses cannot be robbed at the same time. Then if the i-th room is robbed, the i-1-th room cannot be robbed, and the maximum amount of robbing the first i room is dp[i].

So get the recursion formula:

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

code show as below:

class Solution {
public:
    int rob(vector<int>& nums) {
        vector<int> dp(nums.size(),0);
        int len = nums.size();
        
        if(len <= 0){
            return 0;
        }
        
        if(len == 1){
            return nums[0];
        }
        
        if(len == 2){
            return max(nums[0],nums[1]);
        }
        
        dp[0] = nums[0];
        dp[1] = max(nums[0],nums[1]);
        
        for(int i = 2;i < len; ++i){
            dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
        }
        
        return dp[len-1];
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325424767&siteId=291194637