描述:
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 int rob(int[] nums) { if(nums==null) return 0; int len=nums.length; int maxProfit[]=null; if(len==0) return 0; else if(len==1) return nums[0]; else if(len==2) return Math.max(nums[0],nums[1]); else { maxProfit=new int[len]; maxProfit[0]=nums[0]; maxProfit[1]=Math.max(nums[0],nums[1]); for(int i=2;i<len;i++) maxProfit[i]=Math.max(maxProfit[i-1],maxProfit[i-2]+nums[i]); } return maxProfit[len-1]; }
时间: 2024-10-29 19:11:29