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
< ? php function sum ( $ a , $ n ) { $ maxVal = $ a [ 0 ] ; $ maxCount = 1 ; $ secondMax = PHP_INT_MIN ; $ secondMaxCount ; for ( $ 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 * ( $ maxCount - 1 ) / 2 ; return $ secondMaxCount ; } $ array = array ( 1 , 1 , 1 , 2 , 2 , 2 , 3 ) ; $ n = count ( $ array ) ; echo sum ( $ array , $ n ) ; ? >