Search code examples
c++algorithmcounttestcase

Count of Maximum , Passing Test cases but WA


Getting error in this code, even though it passed the basic test cases. But still, it gives the wrong answer.

Cannot find the test case where it fails, Solution to Codechef Count of maximum problem. I think a part of the code is making it fail for a certain test case(s).

Can anyone help me find the error in this code, please?

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int k;
    cin >> k;
    for (int j = 0; j < k; j++) 
    {
        int n;
        cin >> n;
        int a[n];
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        int maxCount = 0;
        int number;
        int index = 0;

        for (int i = 0; i < n; i++) 
        {
            int count = 0;
            for (int l = 0; l < n; l++)
            {
                if (a[i] == a[l])
                {
                    count++;
                    if (count > maxCount) 
                    {
                        maxCount = count;
                        index = i;
                    }
                    if (count == maxCount) {
                        (a[i] > a[index]) ? number = a[index] : number = a[i];
                    }
                }
            }
        }
        cout << number << " " << maxCount << endl;
    }
}

Solution

  • Your number variable is redundant. You need to track theindex of the elements in the array.

    That means, change this line

     (a[i] > a[index]) ? number = a[index] : number = a[i];
    

    to

    (a[i] > a[index]) ? index = index : index = i;
    

    and print

    std::cout << a[index] << " " << maxCount << std::endl;