Maximum difference between frequency of two elements such that element having greater frequency is also greater | Efficient C # program to find maximum difference between frequency of any two elements such that element with greater frequency is also greater in value . ; Return the maximum difference between frequencies of any two elements such that element with greater frequency is also greater in value . ; Finding the frequency of each element . ; Sorting the distinct element ; Iterate through all sorted distinct elements . For each distinct element , maintaining the element with minimum frequency than that element and also finding the maximum frequency difference ; Driver code
using System . Collections . Generic ; using System ; class GFG { static int maxdiff ( int [ ] arr , int n ) { Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; List < int > dist = new List < int > ( ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . ContainsKey ( arr [ i ] ) == false ) { dist . Add ( arr [ i ] ) ; j ++ ; } if ( freq . ContainsKey ( arr [ i ] ) ) freq [ arr [ i ] ] ++ ; else freq [ arr [ i ] ] = 1 ; } dist . Sort ( ) ; int min_freq = n + 1 ; int ans = 0 ; for ( int i = 0 ; i < j ; i ++ ) { int cur_freq = freq [ dist [ i ] ] ; ans = Math . Max ( ans , cur_freq - min_freq ) ; min_freq = Math . Min ( min_freq , cur_freq ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 1 , 3 , 2 , 3 , 2 } ; int n = arr . Length ; Console . WriteLine ( maxdiff ( arr , n ) ) ; } }