House Robber II

来源:互联网 发布:星际战甲漂亮捏脸数据 编辑:程序博客网 时间:2024/06/09 13:45

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


是rob 1 的变形,因为0 跟nums.length-1 不能同时取,所以算两次。

代码:

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]);        return Math.max(robSub(nums, 0, nums.length-2), robSub(nums, 1, nums.length-1));    }        private int robSub(int nums[], int i, int j){        int[] dp = new int[nums.length];        dp[i] = nums[i];        dp[i+1] = Math.max(nums[i], nums[i+1]);        for(int x = i+2;x<=j;x++){            dp[x] = Math.max(dp[x-2]+nums[x], dp[x-1]);        }        return dp[j];    }


0 0
原创粉丝点击