LeetCode House Robber

来源:互联网 发布:黑魂3 狼骑士大盾 数据 编辑:程序博客网 时间:2024/05/03 02:29

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);    }





1 0
原创粉丝点击