Maximum Count of pairs having equal Sum based on the given conditions | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCount ( vector < int > & freq , int mini , int maxi ) { int n = freq . size ( ) - 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 += min ( freq [ firElement ] , freq [ sum - firElement ] ) ; } } if ( sum % 2 == 0 ) { possiblePair += freq [ sum / 2 ] / 2 ; } ans = max ( ans , possiblePair ) ; } return ans ; } int countofPairs ( vector < int > & a ) { int n = a . size ( ) ; int mini = * min_element ( a . begin ( ) , a . end ( ) ) , maxi = * max_element ( a . begin ( ) , a . end ( ) ) ; vector < int > freq ( n + 1 , 0 ) ; for ( int i = 0 ; i < n ; ++ i ) freq [ a [ i ] ] ++ ; return maxCount ( freq , mini , maxi ) ; } int main ( ) { vector < int > a = { 1 , 2 , 4 , 3 , 3 , 5 , 6 } ; cout << countofPairs ( a ) << endl ; }