LeetCode 213: House Robber II

题目描述

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.

题目本质:在House Robber I的基础上,增加一个考虑:不能同时抢劫第一个和最后一个house。因此,可以分别去掉头尾的house,然后在子数组中用I中的方法找到最大和,从头尾的两个最大和中再选较大的那个作为最终的输出。

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
            
        int len = nums.length;
        if(len == 1)
            return nums[0];
        if(len == 2)
            return Math.max(nums[0], nums[1]);
    
        return Math.max(sub_rob(nums,0,len-2), sub_rob(nums,1,len-1));
    }
    
    public int sub_rob(int[] nums, int start, int end){
        int len = end - start + 1;

        int temp0 = 0, temp1 = nums[start];
        int temp = 0;

        for(int i = 1; i < len; i++){
            temp = Math.max(temp0, temp1);
            temp1 = temp0 + nums[start+i];
            temp0 = temp;
        }

        return Math.max(temp0, temp1);
    }
}

你可能感兴趣的:(LeetCode 213: House Robber II)