Number of pairs with maximum sum | function to find the number of maximum pair sums ; Find maximum and second maximum elements . Also find their counts . ; If maximum element appears more than once . ; If maximum element appears only once . ; Driver Code
function sum ( a , n ) { let maxVal = a [ 0 ] , maxCount = 1 ; let secondMax = Number . MIN_VALUE ; let secondMaxCount = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( a [ i ] == maxVal ) maxCount ++ ; else if ( a [ i ] > maxVal ) { secondMax = maxVal ; secondMaxCount = maxCount ; maxVal = a [ i ] ; maxCount = 1 ; } else if ( a [ i ] == secondMax ) { secondMax = a [ i ] ; secondMaxCount ++ ; } else if ( a [ i ] > secondMax ) { secondMax = a [ i ] ; secondMaxCount = 1 ; } } if ( maxCount > 1 ) return maxCount * parseInt ( ( maxCount - 1 ) / 2 , 10 ) ; return secondMaxCount ; } let array = [ 1 , 1 , 1 , 2 , 2 , 2 , 3 ] ; let n = array . length ; document . write ( sum ( array , n ) ) ;