740. Delete and Earn
Medium
71061FavoriteShare
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.
Example 1:
Input: nums = [3, 4, 2] Output: 6 Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted. Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
Input: nums = [2, 2, 3, 3, 3, 4] Output: 9 Explanation: Delete 3 to earn 3 points, deleting both 2's and the 4. Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. 9 total points are earned.
Note:
- The length of
nums
is at most20000
. - Each element
nums[i]
is an integer in the range[1, 10000]
.
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
sort(nums.begin(),nums.end());
map<int,int> mp;
for(int i=0;i<nums.size();i++) mp[nums[i]]+=nums[i];
int max1=0,max2=0;
//max1:取当前数的最大和
//max2:不取当前数的最大和
map<int,int>::iterator it1,it2;
for(it1=mp.begin();it1!=mp.end();it1++){
if(it1==mp.begin()){
max1=it1->second;
max2=0;
}else{
int tmax1=max1,tmax2=max2;
max2=max(tmax1,tmax2);//不取当前数的最大值=max(取前一个数的最大值,不取前一个数的最大值)
if(it1->first==it2->first+1) max1=tmax2+it1->second;
//it2是it1的前一个,map是有序的。因为上一轮末尾,it2=it1,而这一轮开头,it1++
//如果it2与it1的键值相邻,即当前数与上一个数是相邻的,那么取当前数的最大值=不取上一个数的最大值+当前数值
else max1=max2+it1->second;
//如果it2与it1的键值不相邻,那么取当前数的最大值=不取当前数的最大值+当前数值
}
it2=it1;//it2要跟上
}
return max(max1,max2);
}
};
- Runtime: 8 ms, faster than 79.76% of C++ online submissions for Delete and Earn.
- Memory Usage: 9.4 MB, less than 75.00% of C++ online submissions for Delete and Earn.
- Next challenges:
- Count Numbers with Unique Digits
- Bomb Enemy
- Minimum Cost Tree From Leaf Values