Count ways of choosing a pair with maximum difference | JavaScript Code to find no . of Ways of choosing a pair with maximum difference ; To find minimum and maximum of the array ; to find the count of minimum and maximum elements ; Count variables ; condition for all elements equal ; Driver Code
function countPairs ( a , n ) { let mn = Number . MAX_VALUE ; let mx = Number . MIN_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { mn = Math . min ( mn , a [ i ] ) ; mx = Math . max ( mx , a [ i ] ) ; } let c1 = 0 ; let c2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == mn ) c1 ++ ; if ( a [ i ] == mx ) c2 ++ ; } if ( mn == mx ) return n * ( n - 1 ) / 2 ; else return c1 * c2 ; } let a = [ 3 , 2 , 1 , 1 , 3 ] ; let n = a . length ; document . write ( countPairs ( a , n ) ) ;