打印在C ++中出现最大次数的所有和对

在这个问题中,我们得到了n个唯一整数的数组。并且我们必须找到具有最大频率的数组的两个整数之和。该问题有多种解决方案,您需要全部找到它们。

Input : array = { 1, 12, 5, 7, 9, 11}
Output : 16 12

解释-总和16和12出现两次。

5 + 11 = 16 & 7 + 9 = 16
1 + 11 = 12 & 5 + 7 = 12

现在要解决此问题,我们解决该问题的方法是检查每个和对的出现,然后以最大次数打印该对。

解决问题的步骤-

Step 1: Iterate over all pairs.
Step 2: The occurrence of sum pairs is counted using hash-table.
Step 3: After the interation process is done, the sum pair with maximum occurrence is printed.

示例

#include <bits/stdc++.h>
using namespace std;
void sumPairs(int a[], int n){
   unordered_map<int, int> pairSum;
   for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
         pairSum[a[i] + a[j]]++;
      }
   }
   int occur = 0;
   for (auto it : pairSum) {
      if (it.second > occur) {
         occur = it.second;
      }
   }
   for (auto it : pairSum) {
      if (it.second == occur)
         cout << it.first <<"\t";
   }
}
int main(){
   int a[] = { 1, 12, 5, 7, 9, 11 };
   int n = sizeof(a) / sizeof(a[0]);
   cout<<"The sum pairs with max ccurence are : "<<endl;
   sumPairs(a, n);
   return 0;
}

输出结果

出现次数最多的和为-

16 12