Article directory
LeetCode Brushing Notes-Dynamic Programming-day3
198. Robbery
1. Topic
Link to the original title: 198. Robbery
2. Problem-solving ideas
We can use it f[i]
to represent the total amount that the thief went to the first i
room to steal, which can be divided into two situations:
- The thief does not choose
i
the cash in the first room, thenf[i]=f[i-1];
- The thief chooses to steal
i
the cash in the first room, because consecutive rooms cannot be selected, sof[i]=f[i-2]+nums[i];
As shown in the picture:
Figure reproduced: https://www.acwing.com/solution/content/19504/
3. Code
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
vector<int> f(n+1);
if(n<2) return nums[0];
f[0]=nums[0],f[1]=max(nums[0],nums[1]);
for(int i=2;i<n;i++){
f[i]=max(f[i-1],f[i-2]+nums[i]);
}
return f[n-1];
}
};
213. Dajia Palace II
1. Topic
Link to the original title: 213. House Robbery II
2. Problem-solving ideas
From the meaning of the question, we can see that this question has only one more condition compared to 198. Robbery : the first room and the last room cannot be selected at the same time , so we can enumerate these two situations:
- Be sure not to choose the first one, that is, find
[2,n]
the maximum value that can be obtained in the interval - Be sure not to choose the last one, that is, find
[1,n-1]
the maximum value that can be obtained in the interval
Finally, take the maximum value of the two cases.
3. Code
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
vector<int> f(n+1);
if(n<2) return nums[0];
if(n==2) return max(nums[0],nums[1]);
f[0]=nums[0],f[1]=max(nums[0],nums[1]);
for(int i=2;i<n-1;i++){
f[i]=max(f[i-1],f[i-2]+nums[i]);
}
int t1=f[n-2];
f.clear();
f[0]=0,f[1]=nums[1];
for(int i=2;i<n;i++){
f[i]=max(f[i-1],f[i-2]+nums[i]);
}
int t2=f[n-1];
return max(t1,t2);
}
};
740. Delete and get points
1. Topic
Original title link: 740. Delete and get points
2. Problem-solving ideas
Careful analysis of the title shows that this title is similar to 198. House robbery , the difference is that each element may have more than one.
Because the title requires that if you choose num[i]
, you cannot choose elements equal to nums[i] - 1
and , which is equivalent to 198. We cannot choose consecutive rooms in house robbery.nums[i] + 1
We can use to map
record the number of each element, and we can enumerate all elements from 1 to 10000 in the range of numbers given by the title. Use f[i]
to represent the maximum number of points obtained by walking to this point, then:
f[i]=max(f[i-1],f[i-2]+i*cnt[i]);
3. Code
class Solution {
public:
int deleteAndEarn(vector<int>& a) {
map<int,int> cnt;
for(auto x:a) cnt[x]++;
vector<int> f(10001);
f[1]=1*cnt[1];
for(int i=2;i<10001;i++){
f[i]=max(f[i-1],f[i-2]+i*cnt[i]);
}
return f[10000];
}
};