- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Number of pairs with maximum sum in C++
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
Advertisements