# Number of pairs with maximum sum in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Given an array, we need to find the number of pairs with maximum sum. Let's see an example.

Input

arr = [3, 6, 5, 2, 1, 2, 3, 4, 1, 5]

Output

2


The maximum pair sum is 10. There are 2 pairs with maximum sum. They are (5, 5) and (6, 4).

## Algorithm

• Initialise the array with random numbers.
• Initialise the maximum sum to minimum.
• Iterate over the array with two loops.

• Find the maximum sum of pairs.
• Initialise the count to 0.
• Now, iterate over the array again.

• Increment the count if the current pair sum is equal to the maximum pair sum.
• Return the pairs count.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getMaxSumPairsCount(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 count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] + a[j] == maxSum) {
count++;
}
}
}
return count;
}
int main() {
int arr[] = { 3, 4, 5, 2, 1, 2, 3, 4, 1, 5 };
int n = 10;
cout << getMaxSumPairsCount(arr, n) << endl;
return 0;
}

## Output

If you run the above code, then you will get the following result.

1
Updated on 26-Oct-2021 19:25:03