topic
After YJQ finished the 10th week of programming thinking and practice, he came up with a brilliant idea. He made a small modification to the counting problem, which turned it into a counting problem II.
Given a sequence, there are n numbers in it, and each step can take a number, for example, take the i-th number, Ai = x, and get the corresponding score x, but after removing this Ai, x+1 and x-1 ( If there is Aj = x+1 or Aj = x-1, it will become inaccessible (but if there is Aj = x, you can continue to take this x). Find the maximum score.
This question is a little different from what was taught in class, but the core is the same, you need to think about it yourself.
Input
The first line contains an integer n (1 ≤ n ≤ 105), which represents the number of elements in the number. The
second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 105)
Output
Output an integer: n you can get the maximum score.
Ideas
a[i] Record the number of numbers i appear in the array.
Convert dp[i] to the maximum score that can be obtained considering only the numbers 1~i,
dp[i]=max(dp[i-1],dp[ i-2]+a[i]*i)
error
1. Note that the array should be stored in long long
Code
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=1e5+10;
long long a[maxn]={
0};
long long dp[maxn];
int main()
{
long long n,tmp,maxx=0;
memset(a,0,sizeof(a));
cin>>n;
for(int i=0;i<n;i++)
{
cin>>tmp;
a[tmp]++;
if(maxx<tmp)
maxx=tmp;
}
dp[0]=0;
dp[1]=a[1];
for(int i=2;i<=maxx;i++)
dp[i]=max(dp[i-1],dp[i-2]+a[i]*i);
cout<<dp[maxx]<<endl;
return 0;
}