213. House Robber II - jiejackyzhang/leetcode-note GitHub Wiki

Note: This is an extension of 198. 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.

唯一的差别在于这里是个circle。 因此nums[0]与nums[nums.length-1]互为约束。

解题思路为想办法把这个circle拆开,而转化为house robber 1的问题。 这里我们考虑如果nums[0]不rob,则就是求[2,...,length-1]的最大问题; 如果nums[0]rob,则就是求[1,...,length-2]的最大问题。 所以最后的结果就是这两个case中的最大值。

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        return Math.max(rob1(nums, 0, nums.length-2), rob1(nums, 1, nums.length-1));
    }
    
    private int rob1(int[] nums, int start, int end) {
        int include = 0, exclude = 0;
        for(int j = start; j <= end; j++) {
            int i = include, e = exclude;
            include = e + nums[j];
            exclude = Math.max(i, e);
        }
        return Math.max(include, exclude);
    }
}