Maximum Count of pairs having equal Sum based on the given conditions | Java program to implement the above approach ; Function to find the maximum count of pairs having equal sum ; Size of the array ; Iterate through evey sum of pairs possible from the given array ; Count of pairs with given sum ; Check for a possible pair ; Update count of possible pair ; Update the answer by taking the pair which is maximum for every possible sum ; Return the max possible pair ; Function to return the count of pairs ; Size of the array ; Stores the frequencies ; Count the frequency ; Driver Code
class GFG { static int maxCount ( int [ ] freq , int maxi , int mini ) { int n = freq . length - 1 ; int ans = 0 ; for ( int sum = 2 * mini ; sum <= 2 * maxi ; ++ sum ) { int possiblePair = 0 ; for ( int firElement = 1 ; firElement < ( sum + 1 ) / 2 ; firElement ++ ) { if ( sum - firElement <= maxi ) { possiblePair += Math . min ( freq [ firElement ] , freq [ sum - firElement ] ) ; } } if ( sum % 2 == 0 ) { possiblePair += freq [ sum / 2 ] / 2 ; } ans = Math . max ( ans , possiblePair ) ; } return ans ; } static int countofPairs ( int [ ] a ) { int n = a . length ; int [ ] freq = new int [ n + 1 ] ; int maxi = - 1 ; int mini = n + 1 ; for ( int i = 0 ; i < n ; i ++ ) { maxi = Math . max ( maxi , a [ i ] ) ; mini = Math . min ( mini , a [ i ] ) ; } for ( int i = 0 ; i < n ; ++ i ) freq [ a [ i ] ] ++ ; return maxCount ( freq , maxi , mini ) ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 4 , 3 , 3 , 5 , 6 } ; System . out . print ( countofPairs ( a ) + "NEW_LINE"); } }