LeetCode#213-打家劫舍2
/* dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]) */ public class p213 { public int rob(int[] nums) { if(nums.length==0||nums==null)return 0; if(nums.length==1)return nums[0]; return Math.max(robMax(nums,0,nums.length-2),robMax(nums,1,nums.length-1)); } private int robMax(int nums[],int l,int r){ int pre2=0,pre1=0; for(int i=l;i<=r;i++){ int tmp=Math.max(pre2+nums[i],pre1);//tmp为当前dp[i] pre2=pre1; pre1=tmp; } return pre1; } }
运行结果: