Skip to content
Related Articles

Related Articles

Improve Article

Maximum number of pairs of distinct array elements possible by including each element in only one pair

  • Last Updated : 15 Sep, 2021

Given an array arr[] consisting of N integers, the task is to find the maximum number of pairs of array elements such that each pair has a different element and each array element can exist in only one pair

Examples:

Input: arr[] = {4, 5, 4, 5, 4}
Output: 2
Explanation:
There can be 2 pairs forms from the given array i.e., {{4, 5}, {4, 5}}. Therefore, print 2.

Input: arr[] = {2, 3, 2, 1, 3, 1}
Output: 3

Approach: The given problem can be solved by storing the frequency of array elements and generate the pairs using the two highest frequency numbers. This idea can be implemented using Priority Queue. Follow the steps below to solve the problem:



  • Initialize a Map, say M that stores the frequency of array elements.
  • Initialize a priority queue, say, PQ, for implementing the MaxHeap and insert all the frequencies in it.
  • Initialize a variable, say, count as 0 that stores the maximum count of resultant pairs.
  • Traverse the priority queue PQ until its size is greater than 1 and perform the following steps:
  • After completing the above steps, print the value count as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the maximum number
// of pairs having different element
// from the given array
int maximumPairs(int a[], int n)
{
    // Stores the frequency of
    // array element
    map<int, int> freq;
 
    // Stores maximum count of pairs
    int count = 0;
 
    // Increasing the frequency of
    // every element
    for (int i = 0; i < n; ++i)
        freq[a[i]]++;
 
    // Stores the frequencies of array
    // element from highest to lowest
    priority_queue<int> pq;
 
    for (auto itr = freq.begin();
         itr != freq.end();
         itr++) {
 
        // Pushing the frequencies to
        // the priority queue
        pq.push(itr->second);
    }
 
    // Iterate until size of PQ > 1
    while (pq.size() > 1) {
 
        // Stores the top two element
        int freq1 = pq.top();
        pq.pop();
 
        int freq2 = pq.top();
        pq.pop();
 
        // Form the pair between the
        // top two pairs
        count++;
 
        // Decrement the frequencies
        freq1--;
        freq2--;
 
        // Insert updated frequencies
        // if it is greater than 0
        if (freq1 > 0)
            pq.push(freq1);
 
        if (freq2 > 0)
            pq.push(freq2);
    }
 
    // Return the total count of
    // resultant pairs
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 2, 4, 1, 4, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << maximumPairs(arr, N);
 
    return 0;
}

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
    public static int maximumPairs(int[] a, int n)
    {
       
        // Stores the frequency of
        // array element
        HashMap<Integer, Integer> freq
            = new HashMap<Integer, Integer>();
 
        // Stores maximum count of pairs
        int count = 0;
 
        // Increasing the frequency of
        // every element
        for (int i = 0; i < n; i++) {
            int c = a[i];
            if (freq.containsKey(c)) {
                freq.put(c, freq.get(c) + 1);
            }
            else {
 
                freq.put(c, 1);
            }
        }
 
        // Stores the frequencies of array
        // element from highest to lowest
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>();
 
        for (int i = 0;i<n;i++) {
            // Pushing the frequencies to
            // the priority queue
          if(freq.containsKey(a[i])){
            pq.add(freq.get(a[i]));
            freq.remove(a[i]);
          }
        }
           
 
        // Iterate until size of PQ > 1
        while (pq.size() > 1) {
 
            // Stores the top two element
            int freq1 = pq.poll();
 
            int freq2 = pq.poll();
 
            // Form the pair between the
            // top two pairs
            count++;
 
            // Decrement the frequencies
            freq1--;
            freq2--;
 
            // Insert updated frequencies
            // if it is greater than 0
            if (freq1 > 0)
                pq.add(freq1);
 
            if (freq2 > 0)
                pq.add(freq2);
        }
 
        // Return the total count of
        // resultant pairs
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 4, 2, 4, 1, 4, 3 };
        int N = 6;
        System.out.println(maximumPairs(arr, N));
    }
}
 
// This code is contributed by maddler.

Python3




# python 3 program for the above approach
 
# Function to count the maximum number
# of pairs having different element
# from the given array
def maximumPairs(a, n):
   
    # Stores the frequency of
    # array element
    freq = {}
 
    # Stores maximum count of pairs
    count = 0
 
    # Increasing the frequency of
    # every element
    for i in range(n):
        if a[i] in freq:
            freq[a[i]] += 1
        else:
            freq[a[i]] = 1
 
    # Stores the frequencies of array
    # element from highest to lowest
    pq = []
 
    for key,value in freq.items():
        # Pushing the frequencies to
        # the priority queue
        pq.append(value)
 
    pq.sort()
 
    # Iterate until size of PQ > 1
    while (len(pq) > 1):
        # Stores the top two element
        freq1 = pq[len(pq)-1]
        pq = pq[:-1]
 
        freq2 = pq[len(pq)-1]
        pq = pq[:-1]
 
        # Form the pair between the
        # top two pairs
        count += 1
 
        # Decrement the frequencies
        freq1 -= 1
        freq2 -= 1
 
        # Insert updated frequencies
        # if it is greater than 0
        if (freq1 > 0):
            pq.append(freq1)
 
        if (freq2 > 0):
            pq.append(freq2)
 
        pq.sort()
 
    # Return the total count of
    # resultant pairs
    return count
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 2, 4, 1, 4, 3]
    N = len(arr)
    print(maximumPairs(arr, N))
     
    # This code is contributed by ipg2016107.
Output
3

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Another Approach:

This problem can also be solved by just storing the frequency of every elements in an array.  After that we need to find the maximum frequency of an element in the given array. It is confirmed that a pair can not have same values. Suppose we have the elements arr[]={1,1,1,1,2} then one pair will be formed since there is two different values present in the array. Therefore, pairs can not be formed if we are left with the element having same values.  

Below is the implementation :

C++




#include <bits/stdc++.h>
using namespace std;
int main()
{
    int arr[] = { 4, 2, 4, 1, 4, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxi = 0, remain, ans;
    // stores the frequency array
    map<int, int> freq;
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
    for (auto it : freq) {
        // maxi stores the maximum
        // frequency of an element
        maxi = max(maxi, it.second);
    }
    // it stores the sum of all the frequency
    // other than the element which has maximum frequency
    remain = n - maxi;
    if (maxi >= remain) {
        // there will be always zero
        // or more element
        // which will not participate in making pairs
        ans = remain;
    }
    else {
        // if n is odd then except one element
        // we can always form pair for every element
        // if n is even then all the elements can form pair
        ans = n / 2;
    }
    cout << ans;
    freq.clear();
    return 0;
}

Javascript




<script>
let arr = [4, 2, 4, 1, 4, 3];
let n = arr.length;
let maxi = 0,
  remain,
  ans;
   
// stores the frequency array
let freq = new Map();
for (let i = 0; i < n; i++) {
  if (freq.has(arr[i])) {
    freq.set(arr[i], freq.get(arr[i]) + 1);
  } else {
    freq.set(arr[i], 1);
  }
}
 
for (let it of freq)
{
 
  // maxi stores the maximum
  // frequency of an element
  maxi = Math.max(maxi, it[1]);
}
 
// it stores the sum of all the frequency
// other than the element which has maximum frequency
remain = n - maxi;
if (maxi >= remain)
{
 
  // there will be always zero
  // or more element
  // which will not participate in making pairs
  ans = remain;
}
else
{
 
  // if n is odd then except one element
  // we can always form pair for every element
  // if n is even then all the elements can form pair
  ans = Math.floor(n / 2);
}
document.write(ans);
freq.clear();
 
// This code is contributed by gfgking.
</script>
Output
3

Time Complexity of this approach is O(N) since we are traversing through all the elements to form the frequency array.
Auxiliary Space is O(N).

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :