House Robber II

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

House Robber的变形题目,在这个题目中要求收尾两个元素不可以同时选择。我们可以分为两种情况,第一种情况是选择了第一个元素,那么最后一个元素肯定不能选,我们求出这种情况下的最大值max1;第二种情况是不选择第一个元素,那么最后一个元素可以选择,我们同样求出这种情况的下的最大值max2,然后我们返回max1和max2中较大者即可。代码如下:
public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        if(nums.length == 2) return Math.max(nums[0], nums[1]);
        int max = 0;
        int[] dp = new int[nums.length];
        dp[1] = nums[0];
        for(int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]);
        }
        max = dp[nums.length - 1];
        Arrays.fill(dp, 0);
        dp[1] = nums[1];
        for(int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return Math.max(max, dp[nums.length - 1]);
    }
}

你可能感兴趣的:(动态规划)