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 . ; finding difference such that element having greater frequency is also greater in value . ; Driver code
function maxdiff ( arr , n ) { let freq = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) freq . set ( arr [ i ] , freq . get ( arr [ i ] ) == null ? 1 : freq . get ( arr [ i ] ) + 1 ) ; let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) { if ( freq . get ( arr [ i ] ) > freq . get ( arr [ j ] ) && arr [ i ] > arr [ j ] ) ans = Math . max ( ans , freq . get ( arr [ i ] ) - freq . get ( arr [ j ] ) ) ; else if ( freq . get ( arr [ i ] ) < freq . get ( arr [ j ] ) && arr [ i ] < arr [ j ] ) ans = Math . max ( ans , freq . get ( arr [ j ] ) - freq . get ( arr [ i ] ) ) ; } } return ans ; } let arr = [ 3 , 1 , 3 , 2 , 3 , 2 ] ; let n = arr . length ; document . write ( maxdiff ( arr , n ) ) ;