题目
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.
答案
class Solution {
public int rob(int[] nums) {
int m = nums.length;
int[] dp = new int[m];
if(nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
if(nums.length == 2) return Math.max(nums[0], nums[1]);
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i = 2; i < m; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[m - 1];
}
}
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n == 0) return 0;
// Define f[i][0] to mean: max number of coins we can steal from house i...n-1 (if we don't steal from i)
// Define f[i][1] to mean: max number of coins we can steal from house i...n-1 (if we steal from i)
int[][] f = new int[n][2];
f[n - 1][0] = 0;
f[n - 1][1] = nums[n - 1];
for(int i = n - 2; i >= 0; i--) {
f[i][0] = Math.max(f[i + 1][0], f[i + 1][1]);
f[i][1] = f[i + 1][0] + nums[i];
}
return Math.max(f[0][0], f[0][1]);
}
}