Saturday, September 24, 2016

[LintCode] 534 House Robber II 解题报告

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
Given [3, 6, 4], return 6.


思路
和House Robber I一样的思路。不同在于怎么解这个环的问题。
环对解的限制就是:不能同时抢第1个和最后一个房子。
那么我们把题分解成:
1. 不能抢最后一个房子
2. 不能抢第一个房子
然后取最大。
时间复杂度O(n)。空间复杂度O(1)。

Code
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.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        return Math.max(rob(nums, 0, nums.length - 2), 
                        rob(nums, 1, nums.length - 1));
    }
    
    public int rob(int[] nums, int start, int end) {
        if (start == end) {
            return nums[start];
        }

        int prevPrev = 0;
        int prev = nums[start];
        int curr = prev;
        for (int i = start + 1; i <= end; i++) {
            curr = Math.max(prev, prevPrev + nums[i]);
            prevPrev = prev;
            prev = curr;
        }
        
        return curr;
    }
}