Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Guys I am new to competitive programming I was solving a problemhttps://codeforces.com/problemset/problem/455/A ,I took a solution and try it to understand it ,i get 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];
    }


What I have tried:

BUT AS YOU CAN SEE THAT THE LOOP IS RUNNING MAX(100005) EVEN FOR SMALL TEST CASES ,WHEN I TRY TO OPTIMIZE THAT I CAME UP WITH THE 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];


}



BUT THIS IS GIVING WRONG ANSWER ON TEST CASE 12 https://codeforces.com/contest/455/submission/47841668

Can anyone tell me where i did the mistake ? Why that competitive programmer that kind of mistake is that normal?
Posted
Updated 3-Jan-19 7:46am
Comments
Richard MacCutchan 2-Jan-19 9:31am    
1. Please do not shout: using upper case is considered shouting.
2. What is the actual problem with your code?
Rick York 2-Jan-19 17:20pm    
Your best bet is to use the debugger on the case that fails.

1 solution

This is the typical use case for the debugger. Your rist issue is that your output is very little. A better information about the running state of the code is important.

My tip is that your res is wrong and/or not needed.
C++
//initial set all to zero
long long dp[100005]={0};
long long count1[100005]={0};
 
for(int i=2;i<(n+2);i++){
        dp[i]=max(dp[i-1],dp[i-2]+i*count1[i]);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900