House Robber II

    xiaoxiao2021-12-14  21

    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]; }

    转载请注明原文地址: https://ju.6miu.com/read-972071.html

    最新回复(0)