Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 213. House Robber II

Rain Hu

213. House Robber II


一、題目

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system 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:

Example 3:

Constraints:


二、分析

三、解題

1. Dynamic Programming

int rob(vector<int>& nums, int lo, int hi) {
    vector<vector<int>> dp(hi, vector<int>(2, 0));
    dp[lo][1] = nums[lo];
    for (int i = lo+1; i < hi; 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[hi-1][0], dp[hi-1][1]);
}
int rob(vector<int>& nums) {
    int n = nums.size();
    if (n <= 3) return *max_element(nums.begin(), nums.end());
    return max(rob(nums, 0, n-1), rob(nums, 1, n));
}

2. Dynamic Programming(SC optimized)

int rob(vector<int>& nums, int lo, int hi) {
    int robbed = nums[lo];
    int passed = 0;
    for (int i = lo+1; i < hi; i++) {
        int tmp = robbed;
        robbed = passed + nums[i];
        passed = max(tmp, passed);
    }
    return max(robbed, passed);
}
int rob(vector<int>& nums) {
    int n = nums.size();
    if (n <= 3) return *max_element(nums.begin(), nums.end());
    return max(rob(nums, 0, n-1), rob(nums, 1, n));
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 374. Guess Number Higher or Lower
Next
[LeetCode] 198. House Robber