题目内容
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.
题目分析
这是一道简单的动态规划问题,要记录选择该节点与不选择该节点,两种 情况,那个值比较大,选择大的值作为该节点的最终值。
public class Solution { public int rob(int[] nums) {
//if nums is null or length 0, return 0
if(nums==null || nums.length==0)
return 0;
//if only 1 element is present,return it as the answer
if(nums.length==1)
return nums[0];
//array to store the maxProfit attained
int[] maxProfit=new int[nums.length];
//assign fisrt value
maxProfit[0]=nums[0];
//second value is higher of first and second
maxProfit[1]=Math.max(nums[0],nums[1]);
//do dynamic programming for subsequent values
for(int i=2;i<nums.length;i++)
{
maxProfit[i]=Math.max(maxProfit[i-2]+nums[i],maxProfit[i-1]);
}
//return the last value as answer
return maxProfit[nums.length-1];
}
}
public class Solution {
public int rob(int[] nums) {
if(nums==null||nums.length==0){
return 0;
}
int n0 = 0; // 记录没有选择当前houses时的获取的最大金额
int n1 = 0; // 记录选择当前houses时的获取的最大金额
for(int i=0; i<nums.length; i++){
int tmp = n0;
n0 = Math.max(n0,n1); //没有选择当前houses,那么它等于上次选择了或没选择的最大值
n1 = tmp+nums[i]; //选择了当前houses,值只能等于上次没选择的+当前houses的money
}
return Math.max(n0, n1);
}
}