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.
Example
Given [3, 8, 4], return 8.
Notes:
- Single Sequence DP
- State: f[i] represents the maximal amount which the robber can get at i
- Function: f[i] = max(f[i-1], f[i-2]+A[i-1])
- Initial: f[0] = 0; f[1] = A[0];
- Answer: f[n]
- Time: O(n), Space: O(n)
- Optimize: Space -> O(1), rolling array
Space O(n), thinking use this, and then improve
public long houseRobber1(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int n = A.length;
long[] f = new long[n+1];
f[0] = 0;
f[1] = A[0];
for (int i = 2; i <= A.length; ++i) {
f[i] = Math.max(f[i-1], f[i-2]+A[i-1]);
}
return f[n];
}
Rolling Array
public long houseRobber(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int n = A.length;
long[] f = new long[2];
f[0] = 0;
f[1] = A[0];
for (int i = 2; i <= A.length; ++i) {
f[i%2] = Math.max(f[(i-1)%2], f[(i-2)%2]+A[i-1]);
}
return f[n%2];
}
Two variants
public long houseRobber2(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
long pp = 0;
long p = A[0];
long current = A[0];
for (int i = 1; i < A.length; ++i) {
current = Math.max(p, pp + A[i]);
pp = p;
p = current;
}
return current;
}