Probability of choosing a random pair with maximum sum in an array | CPP program of choosing a random pair such that A [ i ] + A [ j ] is maximum . ; 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 ++ ; frequency of first maximum ; cnt2 ++ ; frequency of second maximum ; Returns probability of choosing a pair with maximum sum . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxSumPairs ( int a [ ] , int n ) { int first = INT_MIN , second = INT_MIN ; for ( int 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 ] ; } int cnt1 = 0 , cnt2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == first ) if ( a [ i ] == second ) } if ( cnt1 == 1 ) return cnt2 ; if ( cnt1 > 1 ) return cnt1 * ( cnt1 - 1 ) / 2 ; } float findMaxSumProbability ( int a [ ] , int n ) { int total = n * ( n - 1 ) / 2 ; int max_sum_pairs = countMaxSumPairs ( a , n ) ; return ( float ) max_sum_pairs / ( float ) total ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMaxSumProbability ( a , n ) ; return 0 ; }