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

LeetCode House Robber

时间:2015-04-20 13:13:33      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

思路分析:典型的动态规划,和求最大和子数组有点类似,global[i] 表示num[0...i]之间的最优解,那么DP方程可以写作global[i] = Max(global[i-2] +  num[i], global[i-1]),分别对应于取num[i](此时不能取num[i-1])和不num[i]的最优解,然后取max即可。是一个一维DP,时间和空间复杂度都是O(n)。

AC Code

public class Solution {
    public int rob(int[] num) {
        //1218
        int n = num.length;
        if(n == 0) return 0;
        if(n == 1) return num[0];
        
        int []global = new int [n];
        global[0] = num[0];
        global[1] = Math.max(num[0], num[1]);
        for(int i = 2; i < n; i++){
            global[i] = Math.max(global[i-2] + num[i], global[i-1]);//Max(chooseNum[i], notChooseNum[i])
        }
        return global[n-1];
        //1224
    }
}
优化后只有O(1)空间的代码如下,分别用a和b对奇数index和偶数index的数取local max,每次计算要更新全局max。
 public int rob(int[] num) {
        if(num == null || num.length  == 0) return 0;
        int a = 0; //odd
        int b = 0; //even
        
        for(int i = 0; i < num.length; i++){
            if(i%2 == 0){
                b += num[i];
                b = Math.max(a, b);
            } else{
                a += num[i];
                a = Math.max(a, b);
            }
        }
        return Math.max(a,b);
    }





LeetCode House Robber

标签:

原文地址:http://blog.csdn.net/yangliuy/article/details/45148549

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