码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]House Robber

时间:2015-11-27 06:45:12      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

挺有意思的动态规划题目,只和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;
    }
}

 

[LeetCode]House Robber

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/4999529.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!