In: Computer Science
C PROGRAMMING LANGUAGE
Problem title : Bibi's Array
Bibi also has an array containing N elements. Like Lili, Bibi wants to know the highest frequency (most occurrences) and all elements which have that frequency.
Format Input
The first line contains an integer T stating the number of test cases. For each test case, the first line contains a single integer N which indicate the number of element in the array. The next line contains N integers Xi (1≤ i ≤ N ) which indicate i^th element in the array.
Format Output
Consist of T lines where each line has the format "Case #X:Y" , where X is the test case number starting at 1 and Y is the highest frequency. Next line contains all elements which have that frequency sorted in ascending order.
Constraints
¶ 1≤ T ≤ 20
¶ 2 ≤ N ≤ 20.000
¶ 1 ≤ Xi ≤ 2 x 10^5
Sample Input (standard input)
3
8
1 1 2 2 3 4 5 5
8
5 5 4 3 2 2 1 1
4
1 1 1 3
Sample Output (standard output)
Case #1: 2
1 2 5
Case #2: 2
1 2 5
Case #3: 3
1
C CODE:
#include <stdio.h>
int main()
{
int t,n,MaxCount=0;
scanf("%d",&t);
for(int x=0;x<t;x++)
{
scanf("%d",&n);
int arr[n], freq[n];
int i, j, count;
/* Input elements in array */
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
/* Initially initialize frequencies to -1 */
freq[i] = -1;
}
for(i=0; i<n; i++)
{
count = 1;
for(j=i+1; j<n; j++)
{
/* If duplicate element is found */
if(arr[i]==arr[j])
{
count++;
/* Make sure not to count frequency of same element again
*/
freq[j] = 0;
}
}
/* If frequency of current element is not counted */
if(freq[i] != 0)
{
if(count>MaxCount)
{
MaxCount=count;
}
freq[i] = count;
}
}
/*
* Print frequency of each element
*/
int result[n],z=0,c=0;
printf("Case # %d:%d\n",x+1,MaxCount);
for(i=0; i<n; i++)
{
if(freq[i] ==MaxCount)
{
result[z++]=arr[i];
c++;
}
}
//sorting the result array
for(i=0; i<c; i++)
{
for(j=i+1; j<c; j++)
{
if(result[j] <result[i])
{
int tmp = result[i];
result[i] = result[j];
result[j] = tmp;
}
}
}
//printing Elements of array in sorted ascending order
for(i=0; i<c; i++)
{
printf("%d ", result[i]);
}
}
return 0;
}
OUTPUT SCREENSHOT:
I hope you find this solution helpful and please do UPVOTE if you like my effort , Thanks:)