Description

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.

Example

nums =[3,6,4], return6

Solution

这题是House Robber I的引申。因为成环,所以第一个房子和第二个房子不能同时选择。因此只要求包含第一个房子不包含最后一个房子,和不包含第一个房子包含最后一个房子的较大值即可。
注意边界条件,房子个数为1和2时要单独讨论。

public class Solution {
    /*
     * @param nums: An array of non-negative integers.
     * @return: The maximum amount of money you can rob tonight
     */
    public int houseRobber2(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }

        if (nums.length == 1) {
            return nums[0];
        }

        return Math.max(houseRobber2(nums, 0, nums.length - 2), houseRobber2(nums, 1, nums.length - 1));
    }

    private int houseRobber2(int[] nums, int start, int end) {
        if (start > end) {
            return 0;
        }

        if (start == end) {
            return nums[start];
        }

        int[] dp = new int[2];
        dp[start%2] = nums[start];
        dp[(start+1)%2] = Math.max(nums[start], nums[start+1]);
        for (int i = start+2; i <= end; i++) {
            dp[i%2] = Math.max(dp[(i-1)%2] + nums[i], dp[(i+1)%2]);
        }

        return dp[end%2];
    }
}

results matching ""

    No results matching ""