【Leetcode】213. House Robber II

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 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题目类似,只是这次有了环形

加上条件的 DP 问题需要进行一定的转化才能成为标准的 DP 问题,这个转化就成了关键。

这里的关键就是最后那一个房间 N 和第一个房间相连了,可以这么进行转化:

考虑抢劫了第 0 个房间,那么问题就是求抢劫第 [0, N-1] 个房间的最大数。

考虑不抢劫第 0 个房间,那么问题就是求抢劫第 [1, N] 个房间的最大数。

class Solution {
    public int rob(int[] nums) {
        if (nums == null)
            return 0;
        int n = nums.length;
        if (n == 0)
            return 0;
        if (n == 1)
            return nums[0];
        return Math.max(robDP(nums, 0, n - 2), robDP(nums, 1, n - 1));
    }
 
    int robDP(int[] nums, int first, int last) {
        int n = last - first + 1;
        if (n == 0)
            return 0;
        if (n == 1)
            return nums[first];
        int dp[] = new int[n];
        dp[0] = nums[first];
        dp[1] = Math.max(nums[first], nums[first + 1]);
        for (int i = 2; i < n; i++)
            dp[i] = Math.max(dp[i - 2] + nums[first + i], dp[i - 1]);
        return dp[n - 1];
    }
}

你可能感兴趣的:(【Leetcode】213. House Robber II)