【Lintcode】392. House Robber

题目地址:

https://www.lintcode.com/problem/house-robber/description

给定一个数组AA,每个位置代表这个位置的财富值。现允许取任意多位置的财富,但不允许取相邻的。问最多能取多少财富。

思路是动态规划。设f[i]f[i]表示前ii个位置(从00开始取)能取到的最大的财富值。那么f[0]f[0]对应的就是什么也不取,所以f[0]=0f[0]=0。对于位置ii,有两种情况,若取,则能得到的最大财富值为A[i]+f[i2]A[i]+f[i-2];若不取,则能得到的最大财富值为f[i1]f[i-1]。所以f[i]=max{A[i]+f[i2],f[i1]}f[i]=\max\{A[i]+f[i-2], f[i-1]\}代码如下:

public class Solution {
    /**
     * @param A: An array of non-negative integers
     * @return: The maximum amount of money you can rob tonight
     */
    public long houseRobber(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        
        if (A.length == 1) {
            return A[0];
        }
        
        long[] dp = new long[A.length + 1];
        dp[1] = A[0];
        for (int i = 2; i <= A.length; i++) {
            dp[i] = Math.max(dp[i - 1], A[i - 1] + dp[i - 2]);
        }
        
        return dp[A.length];
    }
}

时空复杂度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章