|  | 
|  | 1 | +/* | 
|  | 2 | +You are given an array of integers that contain numbers in random order. Write a program to find and return the number which occurs the maximum times in the given input. | 
|  | 3 | +If two or more elements contend for the maximum frequency, return the element which occurs in the array first. | 
|  | 4 | + | 
|  | 5 | +Input Format: | 
|  | 6 | +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N. | 
|  | 7 | +The following line contains N space separated integers, that denote the value of the elements of the array. | 
|  | 8 | + | 
|  | 9 | +Output Format : | 
|  | 10 | +The first and only line of output contains most frequent element in the given array. | 
|  | 11 | + | 
|  | 12 | +Constraints: | 
|  | 13 | +0 <= N <= 10^8 | 
|  | 14 | +Time Limit: 1 sec | 
|  | 15 | + | 
|  | 16 | +Sample Input 1 : | 
|  | 17 | +13 | 
|  | 18 | +2 12 2 11 12 2 1 2 2 11 12 2 6  | 
|  | 19 | +Sample Output 1 : | 
|  | 20 | +2 | 
|  | 21 | + | 
|  | 22 | +Sample Input 2 : | 
|  | 23 | +3 | 
|  | 24 | +1 4 5 | 
|  | 25 | +Sample Output 2 : | 
|  | 26 | +1 | 
|  | 27 | +*/ | 
|  | 28 | +import java.util.HashMap; | 
|  | 29 | +public class Solution { | 
|  | 30 | + | 
|  | 31 | + public static int maxFrequencyNumber(int[] arr){  | 
|  | 32 | +		/* Your class should be named Solution | 
|  | 33 | +		 * Don't write main(). | 
|  | 34 | +		 * Don't read input, it is passed as function argument. | 
|  | 35 | +		 * Return output and don't print it. | 
|  | 36 | +	 	 * Taking input and printing output is handled automatically. | 
|  | 37 | +		*/ | 
|  | 38 | + HashMap<Integer,Integer> countMap = new HashMap<>(); | 
|  | 39 | + | 
|  | 40 | + for (int i=0;i<arr.length;i++) | 
|  | 41 | + { | 
|  | 42 | + int ele=arr[i]; | 
|  | 43 | + if (countMap.containsKey(ele)) | 
|  | 44 | + { | 
|  | 45 | + countMap.put(ele,countMap.get(ele)+1); | 
|  | 46 | + } | 
|  | 47 | + else | 
|  | 48 | + { | 
|  | 49 | + countMap.put(ele,1); | 
|  | 50 | + } | 
|  | 51 | + | 
|  | 52 | + } | 
|  | 53 | + | 
|  | 54 | + int maxCount = Integer.MIN_VALUE, maxEle = arr[0]; | 
|  | 55 | + for (int i=0;i<arr.length;i++) | 
|  | 56 | + { | 
|  | 57 | + if (countMap.get(arr[i])>maxCount) | 
|  | 58 | + { | 
|  | 59 | + maxCount=countMap.get(arr[i]); | 
|  | 60 | + maxEle=arr[i]; | 
|  | 61 | + } | 
|  | 62 | + } | 
|  | 63 | + return maxEle; | 
|  | 64 | + } | 
|  | 65 | +} | 
0 commit comments