Maximum difference between frequency of two elements such that element having greater frequency is also greater | Efficient Java 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 ; Driven Program
import java . util . * ; class GFG { static int maxdiff ( int arr [ ] , int n ) { HashMap < Integer , Integer > freq = new HashMap < > ( ) ; int [ ] dist = new int [ n ] ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { dist [ j ++ ] = arr [ i ] ; if ( ! freq . containsKey ( arr [ i ] ) ) freq . put ( arr [ i ] , 1 ) ; else freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } Arrays . sort ( dist ) ; int min_freq = n + 1 ; int ans = 0 ; for ( int i = 0 ; i < j ; i ++ ) { int cur_freq = freq . get ( 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 ; System . out . print ( maxdiff ( arr , n ) + "NEW_LINE"); } }