198. House Robber
原创
©著作权归作者所有:来自51CTO博客作者wx62ea2466cca9a的原创作品,请联系作者获取转载授权,否则将追究法律责任
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
public class Solution {
public static int rob(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int len = nums.length;
int[] rt = new int[len];
if (len == 1)
return nums[0];
if (len == 2) {
return nums[0] > nums[1] ? nums[0] : nums[1];
}
for (int i = 0; i < len; i++) {
if (i == 0) {
rt[i] = nums[i];
} else if (i == 1) {
rt[i] = Math.max(rt[i - 1], nums[i]);
} else {
rt[i] = Math.max(rt[i - 1], rt[i - 2] + nums[i]);
}
}
return rt[len - 1] > rt[len - 2] ? rt[len - 1] : rt[len - 2];
}
}
public class Solution {
public static int rob(int[] nums) {
int[] dp=new int[nums.length];
if(nums.length==0) return 0;
if(nums.length==1) return nums[0];
dp[0]=nums[0];
dp[1]=Math.max(nums[1],nums[0]);
for(int i=2;i<nums.length;i++){
dp[i]=Math.max((nums[i]+dp[i-2]),dp[i-1]);
}
return dp[nums.length-1];
}
}