30 Day Challenge Day 12 | Leetcode 198. House Robber

题解

动态规划

Easy

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty()) return 0;
        if(nums.size() == 1) return nums[0];
        if(nums.size() == 2) return max(nums[0], nums[1]);

        int n = nums.size();
        
        // dp1[i]: maximum amount of money for i houses
        vector<int> dp(n);
        
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        
        for(int i = 2; i < n; i++) {
            dp[i] = max(dp[i-2] + nums[i], dp[i-1]);
        }
        
        return dp[n-1];
    }
};

空间优化

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty()) return 0;

        int n = nums.size();
        int prev = 0, curr = nums[0];
        
        for(int i = 1; i < n; i++) {
            int temp = curr;
            curr = max(prev + nums[i], curr);
            prev = temp;
        }
        
        return curr;
    }
};
上一篇:30 Day Challenge Day 7 | Hackerrank: Tree: Huffman Decoding


下一篇:Linux CFS调度器之唤醒抢占--Linux进程的管理与调度(三十)