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
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