# Print all the sum pairs which occur maximum number of times in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n unique integers. And we have to find the sum of two integers of the array which has the maximum frequency. The problem has multiple solutions and you need to find them all.

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

Explanation − sum 16 and 12 occur two times.

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

Now to solve this problem, our approach to the problem is checking the occurrence every sum pair and then print the pair with the maximum number of times.

Steps to solve the problem

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.

## Example

#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;
}

## Output

The sum pairs with max occurrence are −

16 12
Published on 17-Jan-2020 09:42:13