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
int ans = 0 ; for ( int i = 0 ; i < j ; i ++ ) { int cur_freq = freq [ dist [ i ] ] ; ans = max ( ans , cur_freq - min_freq ) ; min_freq = min ( min_freq , cur_freq ) ; } return ans ; }