Help me with MAXCOUNT test cases where my program does not work

What am I getting wrong answer for this program(MAXCOUNT)[from easy]? I have tried all possible test cases ie. for 1 occurence, for all occurence etc…Please help me find a test case where my code does not work.
Thanking in advance.

import java.util.Scanner;
import java.io.PrintWriter;

public class CountofMaximum {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
while(n>0){
int s = sc.nextInt();
int a[] = new int[s];
int count[] = new int[s];
int i,j,max=0,occ=0;
for(i=0;i<s;i++){
a[i] = sc.nextInt();
}
for(i=0;i<s;i++){
for(j=0;j<s;j++){
if(a[i]==a[j]){
count[i]++;
}
}
}
for(i=0;i<s;i++){
if(count[i]>occ){
occ = count[i];
max = a[i];
}
}
pw.print(max+" "+occ);
pw.println();
n–;
}
pw.flush();
sc.close();
}
}

Hello,

your program fails at this input :slight_smile:

1
6
2 1 1 1 2 2

the out put should be

 1 3

As both 2 and 1 have same count but in case of same count you have to print smaller element

but your program gives output as

 2 3

I see you have used an algorithm with O(t*n^2) complexity had it been n>=10^6 ur program would have given a TLE.

I would suggest you make an array count of 1000 elements and initialize with zero.(though better algorithm exists)
Then as u read elements u can update it as count[input]:=count[input]+1
and then get the maximum :slight_smile: . In this case even if you have various elements of same count . u will get to print smallest one :slight_smile:

The algorithm will go as follows:

 1. read t
 2. for i:=1 to t do
 3.    read n
 4.    initialize count woth zero
 5.    for j:=1 to n do
 6.       read tmp
 7.       count[tmp]:=count[tmp]+1;
 8.    endfor
 9.    max:=-1
 10.   for j:=1 to n do
 11.      if(count[j]>max) do
 12.        max:=count[j]
 13.        maxindex=j
 14.      endif
 15.   endfor
 16.   print maxindex" "max
 17. endfor
 18.end

There are a few things I want to suggest.

  1. You should avoid scanner class here. Its really slow.
  2. And read the problem statement more carefully.

Thanks and happy coding :slight_smile:

1 Like

Hey, thanks a lot for everything you did above even though the code was obfuscated (I tried to edit but couldn’t).I will surely apply the algorithm you gave and follow your suggestions.Next time, I’ll try to find my testcase problems myself.
Thanks a lot once again @c0d3_k1ra

ur welcome buddy :slight_smile: happy coding :slight_smile:

//