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 ; cnt1 += 1 frequency of first maximum ; cnt2 += 1 frequency of second maximum ; Returns probability of choosing a pair with maximum sum . ; Driver Code
def countMaxSumPairs ( a , n ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = a [ i ] NEW_LINE DEDENT elif ( a [ i ] > second and a [ i ] != first ) : NEW_LINE INDENT second = a [ i ] NEW_LINE DEDENT DEDENT cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == first ) : NEW_LINE if ( a [ i ] == second ) : NEW_LINE DEDENT if ( cnt1 == 1 ) : NEW_LINE INDENT return cnt2 NEW_LINE DEDENT if ( cnt1 > 1 ) : NEW_LINE INDENT return cnt1 * ( cnt1 - 1 ) / 2 NEW_LINE DEDENT DEDENT def findMaxSumProbability ( a , n ) : NEW_LINE INDENT total = n * ( n - 1 ) / 2 NEW_LINE max_sum_pairs = countMaxSumPairs ( a , n ) NEW_LINE return max_sum_pairs / total NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMaxSumProbability ( a , n ) ) NEW_LINE DEDENT