Maximum Repeating Count (Id-229) JAVA - AVERAGE - PART003

 Maximum Repeating Count (Id-229)

Given an array of integers of length N, the program must find the value which repeats in maximum number of times and print the number. In case of ties, choose the smaller number and print it.


import java.util.*;

public class Hello {
static int mostFrequent(int arr[], int n)
{
Arrays.sort(arr);
int max_count = 1, res = arr[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
String n1=sc.nextLine();
String[] k=n1.split(" ");
int[] arr=new int[k.length];
for(int i=0;i<k.length;i++)
{
arr[i]=Integer.parseInt(k[i]);   
    }
int n = arr.length;
System.out.println(mostFrequent(arr,n));
}
}

Comments

Popular Posts