House Robber 2 - dynamic programming

Question

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.

Notice
This is an extension of House Robber.

Example
nums = [3,6,4], return 6

Idea

Please read the first version first. House Robber 1

The houses changed from linear to circular, which makes things much more complicated. A key trick here is to TURN THE CIRCLE BACK TO A LINE. As shown in the code below, if you remove the first element from the circle, it immediately becomes linear again.

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) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        return Math.max(
              robMax(nums, 0, nums.length - 2),
              robMax(nums, 1, nums.length - 1)
            );
    }
    
    private int robMax(int[] nums, int start, int end) {
        int numOfStates = 2;
        int[] maxTotal = new int[numOfStates];
        if (start == end) return nums[end];
        if (start + 1 == end) 
          return Math.max(nums[start], nums[end]);
        maxTotal[start % 2] = nums[start];
        maxTotal[(start + 1) % 2] = Math.max(nums[start], nums[start + 1]);
        for(int i = start + 2; i <= end; i++)
          maxTotal[i % 2] = Math.max(
                maxTotal[(i - 1) % 2],
                maxTotal[(i - 2) % 2] + nums[i]
              );
        return maxTotal[end % 2];
    }
}

你可能感兴趣的:(House Robber 2 - dynamic programming)