Number of pairs with maximum sum | Java program to count 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 program
import java . io . * ; class GFG { static int sum ( int a [ ] , int n ) { int maxVal = a [ 0 ] , maxCount = 1 ; int secondMax = Integer . MIN_VALUE , secondMaxCount = 0 ; for ( int 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 ; } public static void main ( String [ ] args ) { int array [ ] = { 1 , 1 , 1 , 2 , 2 , 2 , 3 } ; int n = array . length ; System . out . println ( sum ( array , n ) ) ; } }