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
< ? php function countMaxSumPairs ( $ a , $ n ) { $ first = PHP_INT_MIN ; $ second = PHP_INT_MIN ; for ( $ 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 ] ; } $ cnt1 = 0 ; $ cnt2 = 0 ; for ( $ 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 ; } function findMaxSumProbability ( $ a , $ n ) { $ total = $ n * ( $ n - 1 ) / 2 ; $ max_sum_pairs = countMaxSumPairs ( $ a , $ n ) ; return ( float ) $ max_sum_pairs / ( float ) $ total ; } $ a = array ( 1 , 2 , 2 , 3 ) ; $ n = sizeof ( $ a ) ; echo findMaxSumProbability ( $ a , $ n ) ; ? >