- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all the sum pairs which occur maximum number of times in C++
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
- Related Articles
- Number of pairs with maximum sum in C++
- Print all pairs with given sum in C++
- Maximum count of pairs which generate the same sum in C++
- Print all pairs in an unsorted array with equal sum in C++
- Maximum sum of pairs with specific difference in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Maximum sum of pairs with specific difference C++ program
- Sum of XOR of sum of all pairs in an array in C++
- Sum of XOR of all pairs in an array in C++
- Print all pairs of anagrams in a given array of strings in C++
- Find the smallest sum of all indices of unique number pairs summing to a given number in JavaScript
- Maximum modulo of all the pairs of array where arr[i] >= arr[j] in C++
- Print all triplets with given sum in C++
- Print all subarrays with 0 sum in C++
- Python Program to print a specific number of rows with Maximum Sum

Advertisements