📌  相关文章
📜  通过仅将每个元素包含在一对中,可能的不同数组元素对的最大数量

📅  最后修改于: 2021-10-28 02:04:02             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是找到数组元素对的最大数量,使得每对有不同的元素,并且每个数组元素只能存在于一对中

例子:

方法:可以通过存储数组元素的频率并使用两个最高频率数生成对来解决给定的问题。这个想法可以使用优先队列来实现。请按照以下步骤解决问题:

  • 初始化一个 Map,比如存储数组元素频率的M。
  • 初始化一个优先级队列,比如PQ ,用于实现 MaxHeap 并在其中插入所有频率。
  • 初始化一个变量,比如count0 ,它存储结果对的最大计数。
  • 遍历优先级队列PQ,直到其大小大于1 ,执行以下步骤:
    • PQ 中弹出前两个元素。
    • 将弹出元素的值减1,然后将这两个元素再次插入PQ 中
    • count的值增加1
  • 完成上述步骤后,打印值计数作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
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 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 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 freq
            = new HashMap();
 
        // 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 pq
            = new PriorityQueue();
 
        for (int i = 0;i 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.


输出:
3

时间复杂度: O(N*log N)
辅助空间: O(N)