题目
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 everyelement 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.
分析
这是一道动态规划的题目,不过较最简单的动态规划复杂一点的就是它需要对相邻的数字进行必要的处理。因为当我们考虑取一个数字得分的时候会让取其相邻数字得分的情况下的分值改变。因此在此题我使用了两次的动态规划。(对不相领的数字串和相邻数字串的动态规划)
首先我把原先输入乱序的数字排序,然后用一个map将数字对应的分值保存下来,并新建一个vector来记录各个数字,然后首先是外层的处理,当此数字与前一数字不相邻时,结果直接加上它对应的分值,如果不是则对所有相邻数字进行动态规划。
代码如下:
代码
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
if (!nums.empty()) {
sort(nums.begin(), nums.end());
map<int, int> cost;
vector<int> single;
for (int i = 0; i < nums.size(); ++i) {
int count = 1;
while (i + 1 != nums.size() && nums[i] == nums[i + 1]) {
count++;
i++;
}
cost[nums[i]] = count * nums[i];
single.push_back(nums[i]);
}
vector<int> result(single.size(), 0);
result[0] = cost[single[0]];
for (int i = 1; i < single.size(); ++i) {
if (single[i - 1] + 1 != single[i]) {
if (i + 1 != single.size() && single[i + 1] - 1 == single[i]) {
result[i] = cost[single[i]];
}
else {
result[i] = result[i - 1] + cost[single[i]];
}
}
else {
int index = i;
int t_max;
int t_count = 2;
while (i != single.size() && single[i] == single[i - 1] + 1) {
if (t_count == 2) {
result[i] = cost[single[i]];
}
else {
if (t_count > 3) {
result[i] = cost[single[i]] + max(result[i - 2], result[i - 3]);
}
else {
result[i] = result[i - 2] + cost[single[i]];
}
}
++i;
++t_count;
}
--i;
result[i] = max(result[i], result[i - 1]);
if (index != 1) {
result[i] += result[index-2];
}
}
}
return max(result[single.size() - 1], result[single.size() - 2]);
}
else {
return 0;
}
}
};