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算法求解,也可以使用滚动数组进行优化。
基础解法:
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[] arr) {
// write your code here
if (arr == null || arr.length == 0) {
return 0l;
}
long[] f = new long[arr.length + 1];
f[0] = 0;
f[1] = arr[0];
for (int i = 2; i < f.length; i++) {
f[i] = Math.max(f[i - 1], f[i - 2] + arr[i - 1]);
}
return f[arr.length];
}
}
使用滚动数组进行优化的方法:
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] f = new int[3];
f[0] = 0;
f[1] = nums[0];
for (int i = 1; i < nums.length; i++) {
f[(i + 1) % 3] = Math.max(f[i % 3], f[(i - 1) % 3] + nums[i]);
}
return f[nums.length % 3];
}
}