题目地址:
https://www.lintcode.com/problem/house-robber/description
给定一个数组,每个位置代表这个位置的财富值。现允许取任意多位置的财富,但不允许取相邻的。问最多能取多少财富。
思路是动态规划。设表示前个位置(从开始取)能取到的最大的财富值。那么对应的就是什么也不取,所以。对于位置,有两种情况,若取,则能得到的最大财富值为;若不取,则能得到的最大财富值为。所以代码如下:
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];
}
}
时空复杂度。