Probability of choosing a random pair with maximum sum in an array | Function to get max first and second ; If current element is smaller than first , then update both first and second ; If arr [ i ] is in between first and second then update second ; frequency of first maximum ; frequency of second maximum ; Returns probability of choosing a pair with maximum sum . ; Driver code
function countMaxSumPairs ( a , n ) { let first = Number . MIN_VALUE , second = Number . MIN_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] > first ) { second = first ; first = a [ i ] ; } else if ( a [ i ] > second && a [ i ] != first ) second = a [ i ] ; } let cnt1 = 0 , cnt2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == first ) cnt1 ++ ; if ( a [ i ] == second ) cnt2 ++ ; } if ( cnt1 == 1 ) return cnt2 ; if ( cnt1 > 1 ) return cnt1 * ( cnt1 - 1 ) / 2 ; return 0 ; } function findMaxSumProbability ( a , n ) { let total = n * ( n - 1 ) / 2 ; let max_sum_pairs = countMaxSumPairs ( a , n ) ; return max_sum_pairs / total ; } let a = [ 1 , 2 , 2 , 3 ] ; let n = a . length ; ; document . write ( findMaxSumProbability ( a , n ) ) ;