[leetcode]740. Delete and Earn
Analysis
唉 感觉应该GG了,还是好好刷题看论文吧—— [每天刷题并不难0.0]
Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
把相同的数放到以这个数为下标的bucket里面,再定义两个数组take[]和skip[],然后用动态规划解决,方程为:
take[i]=skip[i-1]+n[i]
skip[i]=max(take[i-1], skip[i-1])
Implement
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
vector<int> n(10001, 0);
for(int num:nums)
n[num] += num;
vector<int> take(10001, 0);
vector<int> skip(10001, 0);
for(int i=1; i<10001; i++){
take[i] = skip[i-1]+n[i];
skip[i] = max(skip[i-1], take[i-1]);
}
return max(take[10000], skip[10000]);
}
};