LeetCode 198. House Robber

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.

 

Code: 使用了动态规划,时间复杂度是O(n^2)

public class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = Integer.MIN_VALUE;
        }
        
        if (n < 1){
            return 0;
        }
            
        dp[n-1]=nums[n-1];
        for (int i = n-2; i >=0 ; i--) {
            for (int j = i; j < n; j++) {
                dp[i] = Math.max(dp[i], nums[j]+(j+2 >= n ? 0 : dp[j+2]));
            }
        }
        return dp[0];
    }
}

 

看了网友提交的答案,瞬间觉得我的脑子秀逗了……排最靠前的代码如下,时间复杂度为O(n),速度快了很多

(看了下,思路不是很清楚,有朋友能解惑么?惭愧)

public class Solution {
    public int rob(int[] nums) {
        int prevYes = 0;
        int prevNo = 0;
        for (int num : nums) {
            int temp = prevNo;
            prevNo = Math.max(prevNo, prevYes);
            prevYes = temp + num;
        }
        return Math.max(prevNo, prevYes);
    }
 }

 

posted @ 2017-07-30 11:09  Realvie  阅读(113)  评论(0编辑  收藏  举报