The idea of this question is that the dp
state (what the elements in the array represent) is very good, that is, the maximum amount of money to go to the i-th store
dp equation is: dp[i]=max(dp[i-1],dp [i-2]+nums[i]);
In fact, it corresponds to whether you are not robbed or robbed when you arrive at this house.
Another point to note is not to fall into a misunderstanding of thinking. Think about this question in the opposite direction. You might think if If robbed, dp[i-1] may not be robbed at this time [i-1] but robbed at [i-2], then in this case I can’t dp[i-1]+ Is nums[i]? You need to know this time! You can't think so! You need to think positively! .
In two cases:
1. The i-th house, no robbery:
then dp[i-1]
is the maximum amount of money in the previous house.
2. The i-th house, robbery! :
Then you can't rob the day before, so under the conditions of this looting, the maximum profit of this house is
dp[i-2]+nums[i], (the maximum amount of money of the first two + this house’s money) This is the case of ans.
last: Finally, taking the maximum value of the two cases is the ans of this question
class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
if(nums.length == 1)
return nums[0];
int[] b = new int[nums.length];
b[0] = nums[0];
b[1] = Math.max(b[0],nums[1]);
for(int i = 2;i < nums.length;i++){
b[i] = Math.max(b[i-1],b[i-2]+nums[i]);
}
return b[b.length-1];
}
}