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:
- Pop the top two elements from the PQ.
- Decrement the value of a popped element by 1 and insert both elements again in the PQ.
- Increment the value of count by 1.
- 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 arrayint 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 Codeint 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 arraydef 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 Codeif __name__ == '__main__':Â Â Â Â arr = [4, 2, 4, 1, 4, 3]Â Â Â Â N = len(arr)Â Â Â Â print(maximumPairs(arr, N))Â Â Â Â Â Â Â Â Â # This code is contributed by ipg2016107. |
C#
/*package whatever //do not write package name here */Â
using System;using System.Collections.Generic;Â
public class GFG {Â Â public static int maximumPairs(int[] a, int n) {Â
    // Stores the frequency of    // array element    Dictionary<int, int> freq = new Dictionary<int, int>();Â
    // 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 = freq + 1;      } else {Â
        freq.Add(c, 1);      }    }Â
    // Stores the frequencies of array    // element from highest to lowest    Queue<int> pq = new Queue<int>();Â
    for (int i = 0; i < n; i++) {      // Pushing the frequencies to      // the priority queue      if (freq.ContainsKey(a[i])) {        pq.Enqueue(freq[a[i]]);        freq.Remove(a[i]);      }    }Â
    // Iterate until size of PQ > 1    while (pq.Count > 1) {Â
      // Stores the top two element      int freq1 = pq.Dequeue();Â
      int freq2 = pq.Dequeue();Â
      // 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.Enqueue(freq1);Â
      if (freq2 > 0)        pq.Enqueue(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;    Console.WriteLine(maximumPairs(arr, N));  }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to count the maximum number// of pairs having different element// from the given arrayfunction maximumPairs(a, n){Â
    // Stores the frequency of    // array element    var freq = new Map();Â
    // Stores maximum count of pairs    var count = 0;Â
    // Increasing the frequency of    // every element    for (var i = 0; i < n; ++i)    {        if(freq.has(a[i]))            freq.set(a[i], freq.get(a[i])+1)        else            freq.set(a[i],1)    }Â
    // Stores the frequencies of array    // element from highest to lowest    var pq = [...freq.values()];    pq.sort((a,b)=>a-b);Â
    // Iterate until size of PQ > 1    while (pq.length > 1) {Â
        // Stores the top two element        var freq1 = pq[pq.length-1];        pq.pop();Â
        var freq2 = pq[pq.length-1];        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);Â
        pq.sort((a,b)=>a-b);    }Â
    // Return the total count of    // resultant pairs    return count;}Â
// Driver Codevar arr = [4, 2, 4, 1, 4, 3 ];var N = arr.length;document.write( maximumPairs(arr, N));Â
// This code is contributed by rrrtnx.</script> |
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;} |
Java
import java.util.*;Â
class GFG{Â Â public static void main(String[] args)Â Â {Â Â Â Â int arr[] = { 4, 2, 4, 1, 4, 3 };Â Â Â Â int n = arr.length;Â Â Â Â int maxi = 0, remain, ans;Â
    // stores the frequency array    HashMap<Integer,Integer> freq = new HashMap<>();    for (int i = 0; i < n; i++) {      if(freq.containsKey(arr[i])){        freq.put(arr[i], freq.get(arr[i])+1);      }      else{        freq.put(arr[i], 1);      }    }    for (Map.Entry<Integer,Integer> it : freq.entrySet())    {Â
      // maxi stores the maximum      // frequency of an element      maxi = Math.max(maxi, it.getValue());    }Â
    // 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;    }    System.out.print(ans);  }}Â
// This code is contributed by Rajput-Ji |
Python3
# Python program for the above approacharr = [ 4, 2, 4, 1, 4, 3 ]n = len(arr)maxi = 0Â
# stores the frequency arrayfreq= dict()for i in range(n):    if arr[i] in freq.keys():        freq[arr[i]] += 1    else:        freq[arr[i]] = 1for it in freq:    # maxi stores the maximum    # frequency of an element    maxi = max(maxi, freq[it])     # it stores the sum of all the frequency# other than the element which has maximum frequencyremain = n - maxiif(maxi >= remain):       # there will be always zero    # or more element    # which will not participate in making pairs    ans = remainelse:    # 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//2print(ans)freq.clear()Â
# This code is contributed by Pushpesh Raj |
C#
using System;using System.Collections;using System.Collections.Generic;Â
class GFG{public static void Main(){    int []arr = { 4, 2, 4, 1, 4, 3 };    int n = arr.Length;    int maxi = 0, remain, ans;         // stores the frequency array    Dictionary<int, int> freq =          new Dictionary<int, int>();               for (int i = 0; i < n; i++) {        if (freq.ContainsKey(arr[i]))        {            freq[arr[i]] = freq[arr[i]] + 1;        }        else        {            freq.Add(arr[i], 1);        }    }         foreach (KeyValuePair<int, int> it in freq)    {               // maxi stores the maximum        // frequency of an element        maxi = Math.Max(maxi, it.Value);    }       // 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;    }    Console.Write(ans);}}Â
// This code is contributed by Samim Hossain Mondal. |
Javascript
<script>let arr = [4, 2, 4, 1, 4, 3];let n = arr.length;let maxi = 0,  remain,  ans;   // stores the frequency arraylet 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 frequencyremain = 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> |
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).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More on that Topic: geeksforgeeks.org/maximum-number-of-pairs-of-distinct-array-elements-possible-by-including-each-element-in-only-one-pair/ […]
… [Trackback]
[…] Read More on that Topic: geeksforgeeks.org/maximum-number-of-pairs-of-distinct-array-elements-possible-by-including-each-element-in-only-one-pair/ […]
… [Trackback]
[…] Find More Info here to that Topic: geeksforgeeks.org/maximum-number-of-pairs-of-distinct-array-elements-possible-by-including-each-element-in-only-one-pair/ […]
… [Trackback]
[…] Find More here on that Topic: geeksforgeeks.org/maximum-number-of-pairs-of-distinct-array-elements-possible-by-including-each-element-in-only-one-pair/ […]