1

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;
    }
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 4
    unrelated: you have Variable Length Arrays, which is not the part of STD C++, use `std::vector<>` instead. Also read [why not #include ](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – JeJo Dec 06 '18 at 13:05
  • 2
    If [this is the problem](https://www.codechef.com/problems/MAXCOUNT), the solution is a simple 5 or 6 line program using `std::map`. Second, as pointed out `int a[n]` is not valid C++. Third, even if you're allowed this invalid syntax, if `n` is large, you can blow out the stack. Last, even if your solution was correct, the complexity is `O(n*n)`. Imagine if `n == 1000` -- you would loop a million times. – PaulMcKenzie Dec 06 '18 at 13:24
  • 1
    If you want to see a solution using `std::map` [please see this](http://coliru.stacked-crooked.com/a/f13c2e48e642c1f0). Basically the key is knowing your data structures such as maps, hash tables, etc. Writing naive nested loop solutions will just lead into "time out" errors occurring, even if the solution is correct. – PaulMcKenzie Dec 06 '18 at 13:58
  • Thank you very much , I'll look into these data structures – Niloy Rahman Dec 07 '18 at 08:32

1 Answers1

1

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;
JeJo
  • 30,635
  • 6
  • 49
  • 88