题目:
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 most 20000
.
Each element nums[i]
is an integer in the range [1,
10000]
.
题目分析:
题目意思是从数组中取一个数获得这个数值的point并把这个数删掉,但是之后这个数-1或者+1的数的point都不能得到,如此重复直到没有数可以取,问怎么取可以获得最多的point。
首先我们可以知道所有数值相同的数一旦取了其中一个其他都可以取,也就是数值相同的数对待方法肯定是一样的,因此我们想到用桶来把数值相同的数都变成一个存放他们总和的桶,这样问题就变成了取桶的问题。
然后我们用动态规划的思路,用dp[i]表示0到i号桶能得到的最大point,当我们新增一个桶,我们有两种选择,一种是取一种不取,当我们取这个桶的时候,意味着我们不能取i-1号桶,这时候point变成bucket[i] + dp[i-2],由这个桶的值和还没有i-1号桶的dp[i-2]决定
当我们不取这个桶的时候,意味着情况和只有i-1个桶是一样的,这时候point和dp[i-1]是一样的
因此每新增一个桶,dp[i]为上面两种情况的最大值决定
c++代码:
class Solution {
public:
int max(int a, int b) {
if (b > a) return b;
else return a;
}
int deleteAndEarn(vector<int>& nums) {
int* bucket = new int[10001];
int* dp = new int[10001];
for (int i = 0; i < 10001; i++) {
bucket[i] = 0;
}
for (int i = 0; i < nums.size(); i++) {
bucket[nums[i]] += nums[i];
}
dp[0] = 0;
dp[1] = bucket[1];
for (int i = 2; i < 10001; i++) {
dp[i] = max(dp[i-2]+bucket[i], dp[i-1]);
}
return dp[10000];
}
};