week16
题目
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.
Note:
· The length of nums is at most 20000.
· Each element nums[i] is an integer in the range [1, 10000].
原题地址:https://leetcode.com/problems/delete-and-earn/description/
解析
题目给定一些数(范围在1到10000),如果删除某个数n,则可以earn到这个数但值为n-1和n+1的数会被删除,求能够earn到的最大的值。
思路:可以用一般的动态规划思想来解决这个问题,从值1开始,计算到目前为止能earn到的最大值,对于某个值n,对应的最大值可由公式f(n)=max{f(n-1),f(n-2)+n*numsOf(n)}得到,前者表示取n-1(则n会被删除),后者表示取n(则n-1会被删除),从1开始循环执行最终到10000得到最后结果。
代码
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
vector<int> count(10001, 0);
for (int i = 0; i < nums.size(); ++i) {
++count[nums[i]];
}
int *earn = new int[10001];
earn[1] = count[1];
for (int i = 2; i < 10001; ++i) {
earn[i] = max(earn[i - 1], earn[i - 2] + count[i] * i);
}
return earn[10000];
}
int max(int a, int b) {
return a > b ? a : b;
}
};