Delete and Earn
- 题目
- 代码块
- 想法
Description
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.
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
int delete1 = 0,notdelete1 = 0;
int A[10001] = {0};
int prenum = -1;
for(int i = 0; i < nums.size(); i++){
A[nums[i]] += 1;
}
for(int i = 0; i <= 10000; i++){
int m = max(delete1,notdelete1);
if(A[i] != 0){
if(i != prenum + 1) {
delete1 = i*A[i] + m;
notdelete1 = m;
}
else{
delete1 = notdelete1 + i*A[i];
notdelete1 = m ;
}
prenum = i;
}
}
return max(delete1,notdelete1);
}
};
int main(){
int A[] = {3,4,2};
vector<int> arr1(A,A+3);
Solution S;
cout<<S.deleteAndEarn(arr1);
}
想法
对于一个数,有两种操作,删除和不删除,对于该数来说,删除意味着前面的数一定是没有被删除,所以delete = 之前的notdelete + i*A[i];而不删除和前面没什么关系,前面无论删不删除都不影响现在这个数的不删除,所以如果这个数不删除,值为max(以前的notdelete,以前的delete),从0到10000,循环,最后比较notdelete和delete的值.