Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 198. House Robber

Rain Hu

198. House Robber


一、題目

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Dynamic Programming

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

2. Dynamic Programming(SC optimized)

int rob(vector<int>& nums) {
    int n = nums.size();
    int robbed = nums[0];
    int passed = 0;
    for (int i = 1; i < n; i++) {
        int tmp = robbed;
        robbed = passed + nums[i];
        passed = max(tmp, passed);
    }
    return max(robbed, passed);
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 213. House Robber II
Next
[Algo] 2-5. 動態規劃 Dynamic Programming