Maximum Count of pairs having equal Sum based on the given conditions

Given an array arr[] of length N containing array elements in the range [1, N], the task is to find the maximum number of pairs having equal sum, given that any element from the array can only be part of a single pair.

Examples:

Input: arr[] = {1, 4, 1, 4} 
Output:
Explanation: Pairs {{1, 4}, {1, 4}} have equal sum 5.

Input: arr[] = {1, 2, 4, 3, 3, 5, 6} 
Output:
Explanation: Pairs {{1, 5}, {2, 4}, {3, 3}} have equal sum 6.

Approach: 



The sum of a pair that can be obtained from the array can neither be less than 2 times the minimum element of the array nor greater than 2 times the largest element, thus we find the maximum number of pairs that can be obtained for each of the sums lying between these extremities and output the maximum among these.

The approach to implement this is as follows:

  1. Store the frequencies of all the elements of the given array.
  2. Iterate through every sum lying between the extremities and count the maximum number of pairs we can obtain for each of these sums.
  3. Print the maximum count among all such pairs obtained to be giving the same summations.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum count
// of pairs having equal sum
int maxCount(vector<int>& freq, int mini, int maxi)
{
 
    // Size of the array
    int n = freq.size() - 1;
 
    int ans = 0;
 
    // Iterate through evey sum of pairs
    // possible from the given array
    for (int sum = 2 * mini; sum <= 2 * maxi; ++sum) {
 
        // Count of pairs with given sum
        int possiblePair = 0;
 
        for (int firElement = 1; firElement < (sum + 1) / 2;
             firElement++) {
 
            // Check for a possible pair
            if (sum - firElement <= maxi) {
 
                // Update count of possible pair
                possiblePair += min(freq[firElement],
                                    freq[sum - firElement]);
            }
        }
 
        if (sum % 2 == 0) {
            possiblePair += freq[sum / 2] / 2;
        }
 
        // Update the answer by taking the
        // pair which is maximum
        // for every possible sum
        ans = max(ans, possiblePair);
    }
 
    // Return the max possible pair
    return ans;
}
 
// Function to return the
// count of pairs
int countofPairs(vector<int>& a)
{
 
    // Size of the array
    int n = a.size();
    int mini = *min_element(a.begin(), a.end()),
        maxi = *max_element(a.begin(), a.end());
 
    // Stores the frequencies
    vector<int> freq(n + 1, 0);
 
    // Count the frequecy
    for (int i = 0; i < n; ++i)
        freq[a[i]]++;
 
    return maxCount(freq, mini, maxi);
}
 
// Driver Code
int main()
{
 
    vector<int> a = { 1, 2, 4, 3, 3, 5, 6 };
   
      // Function Call
    cout << countofPairs(a) << endl;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to find the maximum count
# of pairs having equal sum
 
 
def maxCount(freq, maxi, mini):
 
    # Size of the array
    n = len(freq) - 1
 
    ans = 0
 
    # Iterate through evey sum of pairs
    # possible from the given array
    sum = 2*mini
    while sum <= 2 * maxi:
 
        # Count of pairs with given sum
        possiblePair = 0
 
        for firElement in range(1, (sum + 1) // 2):
 
            # Check for a possible pair
            if (sum - firElement <= maxi):
 
                # Update count of possible pair
                possiblePair += min(freq[firElement],
                                    freq[sum - firElement])
 
        sum += 1
 
        if (sum % 2 == 0):
            possiblePair += freq[sum // 2] // 2
 
        # Update the answer by taking the
        # pair which is maximum
        # for every possible sum
        ans = max(ans, possiblePair)
 
    # Return the max possible pair
    return ans
 
# Function to return the
# count of pairs
 
 
def countofPairs(a):
 
    # Size of the array
    n = len(a)
 
    # Stores the frequencies
    freq = [0] * (n + 1)
 
    maxi = -1
    mini = n+1
 
    for i in range(len(a)):
        maxi = max(maxi, a[i])
        mini = min(mini, a[i])
    # Count the frequecy
    for i in range(n):
        freq[a[i]] += 1
 
    return maxCount(freq, maxi, mini)
 
 
# Driver Code
if __name__ == "__main__":
 
    a = [1, 2, 4, 3, 3, 5, 6]
 
    print(countofPairs(a))
 
# This code is contributed by chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG {
 
    // Function to find the maximum count
    // of pairs having equal sum
    static int maxCount(int[] freq)
    {
 
        // Size of the array
        int n = freq.Length - 1;
 
        int ans = 0;
 
        // Iterate through evey sum of pairs
        // possible from the given array
        for (int sum = 2; sum <= 2 * n; ++sum) {
 
            // Count of pairs with given sum
            int possiblePair = 0;
 
            for (int firElement = 1;
                 firElement < (sum + 1) / 2; firElement++) {
 
                // Check for a possible pair
                if (sum - firElement <= n) {
 
                    // Update count of possible pair
                    possiblePair
                        += Math.Min(freq[firElement],
                                    freq[sum - firElement]);
                }
            }
 
            if (sum % 2 == 0) {
                possiblePair += freq[sum / 2] / 2;
            }
 
            // Update the answer by taking the
            // pair which is maximum
            // for every possible sum
            ans = Math.Max(ans, possiblePair);
        }
 
        // Return the max possible pair
        return ans;
    }
 
    // Function to return the
    // count of pairs
    static int countofPairs(int[] a)
    {
 
        // Size of the array
        int n = a.Length;
 
        // Stores the frequencies
        int[] freq = new int[n + 1];
 
        // Count the frequecy
        for (int i = 0; i < n; ++i)
            freq[a[i]]++;
 
        return maxCount(freq);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] a = { 1, 2, 4, 3, 3, 5, 6 };
 
        Console.Write(countofPairs(a) + "\n");
    }
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output

3

Time Complexity: O(N2
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.