Most frequent element in an array | C # program to find the most frequent element in an array ; Insert all elements in hash ; find max frequency . ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int mostFrequent ( int [ ] arr , int n ) { Dictionary < int , int > hp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int key = arr [ i ] ; if ( hp . ContainsKey ( key ) ) { int freq = hp [ key ] ; freq ++ ; hp [ key ] = freq ; } else hp . Add ( key , 1 ) ; } int min_count = 0 , res = - 1 ; foreach ( KeyValuePair < int , int > pair in hp ) { if ( min_count < pair . Value ) { res = pair . Key ; min_count = pair . Value ; } } return res ; } static void Main ( ) { int [ ] arr = new int [ ] { 1 , 5 , 2 , 1 , 3 , 2 , 1 } ; int n = arr . Length ; Console . Write ( mostFrequent ( arr , n ) ) ; } }