213. House Robber II

Description

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

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

Solution

Two-pass iteration, time O(n), space O(1)

把first house和last house分别排除掉计算即可。计算方式和Hose Robber相同。注意处理边界情况。

class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        if (nums.length == 1) {
            return nums[0];
        }
        
        int notRobFirst = rob(nums, 1, nums.length - 1);
        int notRobLast = rob(nums, 0, nums.length - 2);
        return Math.max(notRobFirst, notRobLast);
    }
    
    public int rob(int[] nums, int i, int j) {
        int robPrev = 0;
        int notRobPrev = 0;
        
        while (i <= j) {
            int tmp = robPrev;
            robPrev = nums[i] + notRobPrev;
            notRobPrev = Math.max(tmp, notRobPrev);
            ++i;
        }
        
        return Math.max(robPrev, notRobPrev);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容