November 02, 2019

213. House Robber II

213. House Robber II

分偷第一间房子和不偷第一间房子两种情况。Time = O(n), space = O(n).

class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        if (nums.length == 2) return Math.max(nums[0], nums[1]);
        
        int[] robFirstHouse = new int[nums.length];
        int[] notRobFirstHouse = new int[nums.length];
        
        robFirstHouse[0] = nums[0];
        robFirstHouse[1] = Math.max(nums[0], nums[1]);
        
        notRobFirstHouse[0] = 0;
        notRobFirstHouse[1] = nums[1];
        
        for (int i = 2; i < nums.length; i++) {
            robFirstHouse[i] = Math.max(robFirstHouse[i - 2] + nums[i], robFirstHouse[i - 1]);
            notRobFirstHouse[i] = Math.max(notRobFirstHouse[i - 2] + nums[i], notRobFirstHouse[i - 1]);
        }
        return Math.max(robFirstHouse[nums.length - 2], notRobFirstHouse[nums.length - 1]);
    }
}
comments powered by Disqus