198. House Robbers - easy

2016-12-17  本文已影响8人  沉睡至夏

特别简单题;Linear time, constant space

public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length==0) return 0;
        int n = nums.length;
        if (n == 1) return nums[0];
        if (n == 2) return Math.max(nums[0], nums[1]);
        
        int two_house_before = nums[0], one_house_before = Math.max(nums[0], nums[1]), current_house = 0;
        for (int i=2; i<n; i++) {
            current_house = Math.max(one_house_before, two_house_before + nums[i]);
            two_house_before = one_house_before;
            one_house_before = current_house;
        }
        return current_house;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读