Guys I am new to competitive programming I was solving a problem(455A BOREDOM) ,I took a solution and tried it to understand it. I believe I understand that that well but I have a small doubt.
   #include<bits/stdc++.h>
    using namespace std;
    #define MAX 100005
    long long dp[100005];
        long long count1[100005];
        int main(){
        int n,x;
        cin>>n;
        for(int i=0;i<n;i++){
            cin >> x;
            count1[x]++;
           // res=max(res,x);
        }
        dp[0]=0;
        dp[1]=count1[1];
        for(int i=2;i<MAX;i++){
            dp[i]=max(dp[i-1],dp[i-2]+i*count1[i]);
        }
        cout<<dp[MAX-1];
    }
However as you can see that the loop is running MAX(100005) even for small test cases. When I tried to optimize that I came up with the following solution:
#include<bits/stdc++.h>
using namespace std;
int main(){
    long long dp[100005];
    long long count1[100005];
    int n;
    cin>>n;
    int x;
    int res=-100000;
    for(int i=0;i<n;i++){
        cin >> x;
        count1[x]++;
        res=max(res,x);
    }
    dp[0]=0;
    dp[1]=count1[1];
    for(int i=2;i<=res;i++){
        dp[i]=max(dp[i-1],dp[i-2]+i*count1[i]);
    }
    cout<< dp[res];
}
However this is giving me the wrong answer on test case 12 https://codeforces.com/contest/455/submission/47841668
The site reported the following error on test case 12:
runtime error: signed integer overflow: 98997 * 8608623459288743937 cannot be represented in type 'long long'
on this line dp[i]=max(dp[i-1],dp[i-2]+i*count1[i]);
Can anyone tell me where i did the mistake ? Why that competitive programmer that kind of mistake is that normal?
 
    