Maximum difference between frequency of two elements such that element having greater frequency is also greater | 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
def maxdiff ( arr , n ) : NEW_LINE INDENT freq = { } NEW_LINE dist = [ 0 ] * n NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in freq ) : NEW_LINE INDENT dist [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE freq [ arr [ i ] ] = 0 NEW_LINE DEDENT if ( arr [ i ] in freq ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT DEDENT dist = dist [ : j ] NEW_LINE dist . sort ( ) NEW_LINE min_freq = n + 1 NEW_LINE ans = 0 NEW_LINE for i in range ( j ) : NEW_LINE INDENT cur_freq = freq [ dist [ i ] ] NEW_LINE ans = max ( ans , cur_freq - min_freq ) NEW_LINE min_freq = min ( min_freq , cur_freq ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 1 , 3 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxdiff ( arr , n ) ) NEW_LINE