【Leetcode】198. House Robber

Topic address:

https://leetcode.com/problems/house-robber/description/

Topic description:

In fact, it is to take non-adjacent numbers from a set of numbers so that their sum is the largest.

Problem solving ideas:

Dynamic programming, in fact, is to judge whether the current number is selected or not, and an array dp is set, and dp[i] represents the value that can be obtained when the i-th number is selected.

The maximum value, compare dp[i-1] (do not take the current number) and dp[i-2]+nums[i] (take the current number) which is larger, that is, the transition equation:

dp[i] = max(dp[i-1],dp[i-2] + nums[i]). Note that you need to initialize dp[0] = nums[0], dp[1] = max(nums[0],nums[1])

Code:

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

        return dp[size - 1];
    }
};

 

Guess you like

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