[LeetCode]House Robber

挺有意思的动态规划题目,只和i-2和i-3家的状态有关,取其中最大值

public class Solution {
    public int rob(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return 0;
        } else if (length == 1) {
            return nums[0];
        } 
        int[] record = new int[length];
        int result = 0;
        record[0] = nums[0];
        record[1] = nums[1];
        result = Math.max(record[0], record[1]);
        for (int i = 2; i < length; i++) {
            int tmp1 = record[i - 2];
            int tmp2 = i > 2 ? record[i - 3] : 0;
            record[i] = nums[i] + Math.max(tmp1, tmp2);
            result = Math.max(result, record[i]);
        }
        return result;
    }
}

 

posted @ 2015-11-27 04:19  Weizheng_Love_Coding  阅读(103)  评论(0编辑  收藏  举报