Getting wrong answer very quickly on a problem

#include
#include
#include

int main() {

int tests = 0;
std::cin >> tests;

while(tests-->0) {
    int N = 0;
    std::cin >> N;
    
    int D = 0;
    std::cin >> D;
    
    
    std::vector<int> theNums(N);
    
    for (int i = 0; i < theNums.size(); ++i) {
        std::cin >> theNums[i];
    }
    
    int removeRange = N - D;
    theNums.erase(theNums.begin() + removeRange, theNums.end());
    
    int sum = 0;
    for (int i = 0; i < theNums.size(); ++i) {
        sum += theNums[i];
    }
    
    std::cout << sum << std::endl;
    
}

return 0;

}

1 Like

Link to problem: https://www.codechef.com/problems/DELSUM

Is it because I am not checking for the case if D is greater than N?
When I run my code on a separate compiler it works fine.

1 Like

I have all the include algorithm, vector, and iostream. It just got cut off for some reason. Apologies.

1 Like

Well, looks like there’s a lot you can improve on.

Ok, now let’s look at the (possible)errors:

  • while(test-->0) : maybe it’s going through all the test cases, or maybe it’s just leaving out the last test case. I haven’t tried it. What I did was while(test--) .
  • std::vector<int> theNums(N); : since the range for the numbers present in the list is not mentioned, the numbers can be of type long long, long, or just short. The safest way is std::vector<long long> theNums(N); .
  • Before theNums.erase(...), you should be sorting the list - so that you can remove the D greatest numbers in the list. I think you were going to use the sort(...) function for that, for which you included the <algorithm> file, but you forgot to add the function later.

Lastly(but it’s quite important for coding practices in C++14), just write using namespace std; after including all the required header files - I had a hard time going through the same std:: multiple times.

You can go through this link for understanding the solution: https://www.codechef.com/viewsolution/24028722

Cheers,
Sumit.

The error was that I forgot to sort the vector :stuck_out_tongue:

Thanks!