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.
一维DP。res[i] = max(res[i - 2] + A[i], res[i-1])。注意res大小越界,需要使用long型数组。
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) {
if(A.length == 0) return 0L;
if(A.length == 1) return A[0];
long[] res = new long[A.length];
res[0] = A[0];
res[1] = Math.max(A[0], A[1]);
for(int i = 2; i < A.length; i++) {
res[i] = Math.max(res[i - 2] + A[i], res[i - 1]);
}
return res[A.length - 1];
}
}
一维DP空间复杂度为O(n)。如果需要O(1)的空间复杂度的话,经过观察,循环中只需要两个变量,res[i-1]和res[i-2]。可以将这两个变量用本地变量储存。每次循环时更新。
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) {
long last = 0, beforeLast = 0, res = 0;
for(int i = 0; i < A.length; i++) {
res = Math.max(last, beforeLast + A[i]);
beforeLast = last;
last = res;
}
return res;
}
}