Description
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input
The first line contains integer n (1 ≤ n ≤ 10^5) that shows how many numbers are in Alex's sequence.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 10^5)
Output
Print a single integer — the maximum number of points that Alex can earn.
Sample Input
9 1 2 1 3 2 2 2 2 3
Sample Output
10
Hint
Consider the test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.
思路:一开始没有想到dp,仔细读题,删数与所给序列顺序无关,只需要统计所有数的个数就可以。然后便发现这是一个线性的简单dp题了,对于一个数i,有两种情况,即i-1选择删掉,则i分数不变,或i-1没有选择而是被i-2连带删掉了,则dp[i]=max(dp[i-1],dp[i-2]+cnt[i]*i),cnt统计数字i'的个数,这里注意就是,对于一串数,其最大值一定是全部删除的。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<math.h>
#include <stack>
#include<map>
#include<stdlib.h>
#include<queue>
#define LL long long
using namespace std;
const int N=1e5+10,M=1e5+10,inf=0x3f3f3f3f;
const LL INF=1e18;
int n,mx;
int ite[N];
LL dp[N];
int main() {
cin>>n;
for(int i=1,temp;i<=n;i++){
scanf("%d",&temp);
ite[temp]++;
if(mx<temp)mx=temp;
}
dp[0]=0,dp[1]=ite[1];
LL ans=0;
for(int i=2;i<=mx;i++){
dp[i]=max(dp[i-1],dp[i-2]+ite[i]*i);
ans=max(dp[i],ans);
}
cout<<dp[mx]<<'\n';
return 0;
}