Maximum number of pairs of distinct array elements possible by including each element in only one pair
Last Updated :
26 May, 2022
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++
#include <bits/stdc++.h>
using namespace std;
int maximumPairs( int a[], int n)
{
map< int , int > freq;
int count = 0;
for ( int i = 0; i < n; ++i)
freq[a[i]]++;
priority_queue< int > pq;
for ( auto itr = freq.begin();
itr != freq.end();
itr++) {
pq.push(itr->second);
}
while (pq.size() > 1) {
int freq1 = pq.top();
pq.pop();
int freq2 = pq.top();
pq.pop();
count++;
freq1--;
freq2--;
if (freq1 > 0)
pq.push(freq1);
if (freq2 > 0)
pq.push(freq2);
}
return count;
}
int main()
{
int arr[] = { 4, 2, 4, 1, 4, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << maximumPairs(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int maximumPairs( int [] a, int n)
{
HashMap<Integer, Integer> freq
= new HashMap<Integer, Integer>();
int count = 0 ;
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 );
}
}
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for ( int i = 0 ;i<n;i++) {
if (freq.containsKey(a[i])){
pq.add(freq.get(a[i]));
freq.remove(a[i]);
}
}
while (pq.size() > 1 ) {
int freq1 = pq.poll();
int freq2 = pq.poll();
count++;
freq1--;
freq2--;
if (freq1 > 0 )
pq.add(freq1);
if (freq2 > 0 )
pq.add(freq2);
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 4 , 2 , 4 , 1 , 4 , 3 };
int N = 6 ;
System.out.println(maximumPairs(arr, N));
}
}
|
Python3
def maximumPairs(a, n):
freq = {}
count = 0
for i in range (n):
if a[i] in freq:
freq[a[i]] + = 1
else :
freq[a[i]] = 1
pq = []
for key,value in freq.items():
pq.append(value)
pq.sort()
while ( len (pq) > 1 ):
freq1 = pq[ len (pq) - 1 ]
pq = pq[: - 1 ]
freq2 = pq[ len (pq) - 1 ]
pq = pq[: - 1 ]
count + = 1
freq1 - = 1
freq2 - = 1
if (freq1 > 0 ):
pq.append(freq1)
if (freq2 > 0 ):
pq.append(freq2)
pq.sort()
return count
if __name__ = = '__main__' :
arr = [ 4 , 2 , 4 , 1 , 4 , 3 ]
N = len (arr)
print (maximumPairs(arr, N))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static int maximumPairs( int [] a, int n) {
Dictionary< int , int > freq = new Dictionary< int , int >();
int count = 0;
for ( int i = 0; i < n; i++) {
int c = a[i];
if (freq.ContainsKey(c)) {
freq = freq + 1;
} else {
freq.Add(c, 1);
}
}
Queue< int > pq = new Queue< int >();
for ( int i = 0; i < n; i++) {
if (freq.ContainsKey(a[i])) {
pq.Enqueue(freq[a[i]]);
freq.Remove(a[i]);
}
}
while (pq.Count > 1) {
int freq1 = pq.Dequeue();
int freq2 = pq.Dequeue();
count++;
freq1--;
freq2--;
if (freq1 > 0)
pq.Enqueue(freq1);
if (freq2 > 0)
pq.Enqueue(freq2);
}
return count;
}
public static void Main(String[] args) {
int []arr = { 4, 2, 4, 1, 4, 3 };
int N = 6;
Console.WriteLine(maximumPairs(arr, N));
}
}
|
Javascript
<script>
function maximumPairs(a, n)
{
var freq = new Map();
var count = 0;
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)
}
var pq = [...freq.values()];
pq.sort((a,b)=>a-b);
while (pq.length > 1) {
var freq1 = pq[pq.length-1];
pq.pop();
var freq2 = pq[pq.length-1];
pq.pop();
count++;
freq1--;
freq2--;
if (freq1 > 0)
pq.push(freq1);
if (freq2 > 0)
pq.push(freq2);
pq.sort((a,b)=>a-b);
}
return count;
}
var arr = [4, 2, 4, 1, 4, 3 ];
var N = arr.length;
document.write( maximumPairs(arr, N));
</script>
|
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;
map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
for ( auto it : freq) {
maxi = max(maxi, it.second);
}
remain = n - maxi;
if (maxi >= remain) {
ans = remain;
}
else {
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;
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 = Math.max(maxi, it.getValue());
}
remain = n - maxi;
if (maxi >= remain)
{
ans = remain;
}
else
{
ans = n / 2 ;
}
System.out.print(ans);
}
}
|
Python3
arr = [ 4 , 2 , 4 , 1 , 4 , 3 ]
n = len (arr)
maxi = 0
freq = dict ()
for i in range (n):
if arr[i] in freq.keys():
freq[arr[i]] + = 1
else :
freq[arr[i]] = 1
for it in freq:
maxi = max (maxi, freq[it])
remain = n - maxi
if (maxi > = remain):
ans = remain
else :
ans = n / / 2
print (ans)
freq.clear()
|
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;
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 = Math.Max(maxi, it.Value);
}
remain = n - maxi;
if (maxi >= remain)
{
ans = remain;
}
else
{
ans = n / 2;
}
Console.Write(ans);
}
}
|
Javascript
<script>
let arr = [4, 2, 4, 1, 4, 3];
let n = arr.length;
let maxi = 0,
remain,
ans;
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 = Math.max(maxi, it[1]);
}
remain = n - maxi;
if (maxi >= remain)
{
ans = remain;
}
else
{
ans = Math.floor(n / 2);
}
document.write(ans);
freq.clear();
</script>
|
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).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...