
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Pairs with Maximum Sum in C++
We need to find a number of all the pairs that has the maximum sum, In a given array of integers. A pair consists of two numbers, and the sum is simply the result of adding them.
We will see multiple solutions to this problem, starting with a naive (brute force) approach and moving to more optimized solutions. Below is the list of approaches we will cover in this article:
- Brute Force approach using two loops
- Max Sum Pairs with Sorting
- Max Sum Pairs Using Hashing
Example
Input:
arr = [3, 6, 5, 2, 1, 2, 3, 4, 1, 5]
Output:
2
The maximum sum of any pair is 10. Two pairs give this sum: (5, 5) and (6, 4). So, the answer is 2.
Brute Force approach using two loops
The brute force solution is the most self-explanatory one. Here, we try every possible pair in the array and calculate their sum. We keep track of the highest sum we encounter. Once we know what the maximum sum is, we go through the array again and check for each pair sum if it matches with maximum we increase the count of pairs.
Let's see the process for counting maximum sum pairs in C++:
-
Initialize the maximum sum: We start by setting the maximum sum to a very low number, like
INT_MIN
(the smallest possible integer value). This ensures that the first pair we encounter will always update the maximum sum. - Find the maximum sum: We use two loops. The first loop picks one number, and the second loop picks another number (after the first one). For every pair, we calculate the sum and compare it with the current maximum sum. If it's larger, we update the maximum sum.
- Count pairs with the maximum sum: After finding the maximum sum, we reset the loops and again check each pair's sum. This time, we count how many pairs give us the maximum sum.
Code Implementation
#include<bits/stdc++.h> using namespace std; int maxSumPairsCnt(int a[], int n) { int maxSum = INT_MIN; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { maxSum = max(maxSum, a[i] + a[j]); } } int cnt = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[i] + a[j] == maxSum) { cnt++; } } } return cnt; } int main() { int arr[] = {3, 4, 5, 2, 1, 2, 3, 4, 1, 5}; int n = 10; cout << maxSumPairsCnt(arr, n) << endl; return 0; }
Time Complexity
The time complexity of this approach is O(n²), where n is the size of the array. This is because we used two nested loops to check each possible pair of numbers. While this solution is simple, it becomes slow as the array size increases.
Explanation
We used a brute force method where every pair in the array was checked, calculated, and compared to find the maximum sum. Once we we got the maximum sum, we looped through the array again for counting how many pairs have this sum. While this is simple and friendly, it has a time complexity of O(n²) due to the double loop for checking all possible pairs. This approach works fine for small arrays but becomes inefficient as the size increases.
Maximum Sum Pairs with Sorting
We can improve our solution by first sorting the array. And once the array is sorted, the two largest elements will be the last two elements in the array. Their sum will be the maximum pair sum.
Sorting also makes counting how many pairs have this sum easier, as similar numbers will be grouped together.
- Sort the array: Once sorted, the last two elements of the array will give the maximum sum.
- Count pairs: We now count how many pairs of numbers sum to this value by using two loops to go through the array.
Now, we understood what we have to do so let's understand through the code ?
#include<bits/stdc++.h> using namespace std; int maxSumPairsCnt(int a[], int n) { sort(a, a + n); // Sort the array int maxSum = a[n - 1] + a[n - 2]; // Sum of two largest elements int cnt = 0; // Count pairs with the max sum for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[i] + a[j] == maxSum) { cnt++; } } } return cnt; } int main() { int arr[] = {3, 4, 5, 2, 1, 2, 3, 4, 1, 5}; int n = 10; cout << maxSumPairsCnt(arr, n) << endl; return 0; }
Time Complexity
The time complexity of sorting the array is O(n log n), and counting pairs still takes O(n²) due to the nested loops. Sorting speeds up finding the maximum sum, but we still need two loops to count pairs.
Explanation
By sorting the array, we quickly identify the maximum sum using the two largest elements at the end of the sorted list. However, we still need to loop through all pairs to count how many sum up to this maximum. Sorting improves finding the largest sum but doesn't fully optimize the counting process, resulting in a time complexity of O(n log n) for sorting and O(n²) for counting.
Max Sum pairs Using HashMap
This approach uses a hash map to count the frequency of each element in the array. By storing how many times each number occurs, we can efficiently find pairs with the maximum sum without using two loops.
- Count the frequency of each element: Use a hash map to track how many times each number appears.
- Find the largest elements: The two largest elements in the array will give the maximum sum. We look for them in the hash map.
-
Count the pairs: Based on the frequency of the two largest numbers, we calculate how many pairs can be formed. If the two numbers are the same, we use the combination formula
nC2
(combinations of two). If they are different, we simply multiply their frequencies.
Below is the code for finding count of maximum sum pairs using hashmap.
#include <bits/stdc++.h> using namespace std; int maxSumPairsCnt(int a[], int n) { unordered_mapfreq; // Count the frequency of each element for (int i = 0; i < n; i++) { freq[a[i]]++; } // Find the two largest elements int max1 = INT_MIN, max2 = INT_MIN; for (auto it : freq) { if (it.first > max1) { max2 = max1; max1 = it.first; } else if (it.first > max2) { max2 = it.first; } } // Calculate the maximum sum int maxSum = max1 + max2; int cnt = 0; // Count pairs if (max1 == max2) { cnt = (freq[max1] * (freq[max1] - 1)) / 2; // nC2 combinations } else { cnt = freq[max1] * freq[max2]; } return cnt; } int main() { int arr[] = {3, 4, 5, 2, 1, 2, 3, 4, 1, 5}; int n = 10; cout << maxSumPairsCnt(arr, n) << endl; return 0; }
Time Complexity
The time complexity is O(n)
This is because we only need to go through the array once to count the frequency of each element, and then we make a constant number of operations (finding the two largest elements and calculating the number of pairs). Therefore, this approach is much faster than the previous ones.
Explanation
This approach uses a hash map to count the frequency of each element in the array. We then find the two largest elements by scanning through the frequency map once. Finally, we compute how many pairs can be formed using these two elements (or the same element if they are identical). This approach avoids double loops and achieves a time complexity of O(n), making it the fastest and most efficient for large datasets