Ideas:
Every time there is an interval, the result of each time depends on the result of the previous time, I think of using dynamic programming
To meet the conditions:
1) Optimal sub-problem: the final optimal solution is generated by each sub-optimal solution
2) Overlapping sub-problems: To calculate the current solution, you have to repeatedly calculate the previous
Code:
class Solution {
public int rob(int[] nums) {
int n=nums.length;
if(n==0) return 0;
if(n==1) return nums[0];
int[] dp=new int[n+1];
//规律:每次初始化前2个,0和1
dp[0]=nums[0];
//注意不是dp[1]=nums[1],因为还有nums[0]
dp[1]=Math.max(dp[0],nums[1]);
for(int i=2;i<n;i++){
//若不选i,则选dp[i-1]
//若选i,则选dp[i-2]+nums[i]
//比较两者哪个更大
dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]);
}
//因为有n个,但下标n-1才是第n个
return dp[n-1];
}
}
break down:
1) Regularity: the first 2 of each initialization, dp[0] and dp[1]
2) The last return is dp[n-1], because there are n, but the subscript n-1 is the nth
3) Satisfy the 2 conditions of dynamic programming:
i) Optimal sub-problem: The final optimal solution is generated by each sub-optimal solution
ii) Overlapping sub-problems: To calculate the current solution, you have to repeatedly calculate the previous
4) To prevent subscript overflow, when dp is declared, the length is added 1 (n+1) on the basis of n
5) Belongs to the second dp form:
The current value depends on all the previously calculated values