Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 213. House Robber II #63

Open
Woodyiiiiiii opened this issue Jun 3, 2020 · 0 comments
Open

LeetCode 213. House Robber II #63

Woodyiiiiiii opened this issue Jun 3, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jun 3, 2020

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 security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

与House Robber I不同的是首尾两个房子不能同时选择。

解法是创建两个数组,第一个长度是n - 1,不考虑最后一个房子;第二个不考虑第一个房子,最后从两个数组分别最后的两个元素(倒数第一,倒数第二个)选择最大的那个和:

class Solution {
    public int rob(int[] nums) {
        int n = nums.length, i = 2;
        if (n <= 0) return 0;
        else if (n == 1) return nums[0];
        else if (n == 2) return Math.max(nums[0], nums[1]);
        int[] dp1 = new int[n - 1];
        int[] dp2 = new int[n];
        dp1[0] = nums[0];
        dp1[1] = Math.max(nums[0], nums[1]);
        dp2[1] = nums[1];
        for (i = 2; i < n - 1; ++i) {
            dp1[i] = Math.max(dp1[i - 2] + nums[i], dp1[i - 1]);
            dp2[i] = Math.max(dp2[i - 2] + nums[i], dp2[i - 1]);
        }
        dp2[i] = Math.max(dp2[i - 2] + nums[i], dp2[i - 1]);
        return Math.max(dp1[n - 2], dp2[n - 1]);
    }
}

当然可以优化空间复杂度,不赘述。


参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant