LeetCode198打家劫舍
class Solution {
public int rob(int[] nums) {
int size = nums.length;
if(size == 1){
return nums[0];
}
int[] dp = new int[size];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for(int i=2;i<size;i++){
dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
}
return dp[size-1];
}
}
LeetCode213打家劫舍2
class Solution {
public int rob(int[] nums) {
int size = nums.length;
if(size == 1){
return nums[0];
}
int ans1 = getRob(nums, 0, size-1);
int ans2 = getRob(nums, 1, size);
return Math.max(ans1, ans2);
}
public int getRob(int[] nums, int start, int end){
if(end-start==1){
return nums[start];
}
int size = end-start + 1;
int[] dp = new int[nums.length];
dp[start] = nums[start];
dp[start+1] = Math.max(nums[start], nums[start+1]);
for(int i=start+2;i<end;i++){
dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i]);
}
return dp[end-1];
}
}