力扣算法学习day31-3
213-打家劫舍 II
题目
![image-20220221001612698](https://i-blog.csdnimg.cn/blog_migrate/38be6056f486a5bfac3fbfa7f09f88f7.png)
![image-20220221001731350](https://i-blog.csdnimg.cn/blog_migrate/08e93a9741242effb1ed7dd9c2d575f9.png)
代码实现
class Solution {
public int rob(int[] nums) {
if(nums.length == 1){
return nums[0];
}
int result1 = robResult(0,nums.length-1,nums);
int result2 = robResult(1,nums.length,nums);
return Math.max(result1,result2);
}
public int robResult(int index1,int index2,int[] nums){
if(index2 - index1 == 1){
return nums[index1];
}
int[] dp = new int[index2 - index1];
dp[0] = nums[index1];
dp[1] = Math.max(nums[index1],nums[index1+1]);
for(int i = 2;i < dp.length;i++){
dp[i] = Math.max(dp[i-1],dp[i-2] + nums[index1+2]);
index1++;
}
return dp[dp.length-1];
}
}