2015年8月29日星期六

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.

public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }      
        if (nums.length == 1) {
            return nums[0];
        }
        int[] maxRob = new int[nums.length + 1];
        int[] maxNoRob = new int[nums.length + 1];
        maxRob[1] = nums[0];
        int maxMoney = 0;
        for (int i = 1; i < nums.length; i++) {
            int n = nums[i];
            if (i != nums.length - 1) {
                maxNoRob[i + 1] = Math.max(maxNoRob[i - 1] + n, maxNoRob[i]);
                maxRob[i + 1] = Math.max(maxRob[i - 1] + n, maxRob[i]);
            } else {
                maxMoney = Math.max(maxRob[i], Math.max(maxNoRob[i - 1] + n, maxNoRob[i]) );
            }
        }
        return maxMoney;
    }
}

=====
public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        int rob = nums[0];
        int noRob = 0;
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            if (i != nums.length - 1) {
                int tmpRob = rob;
                rob = Math.max(rob, noRob + num);
                noRob = tmpRob;
            }
        }
        int res = Math.max(rob, noRob);
       
        rob = 0;
        noRob = 0;
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            int tmpRob = rob;
            rob = Math.max(rob, noRob + num);
            noRob = tmpRob;
        }
        return Math.max(res, Math.max(rob, noRob));
    }
}

没有评论:

发表评论