
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Maximum sum of pairs with specific difference in C++
- Maximum sum of pairs with specific difference C++ program
- Print all the sum pairs which occur maximum number of times in C++
- Maximum count of pairs which generate the same sum in C++
- Count pairs with given sum in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Program to find max number of K-sum pairs in Python
- Python Program to print a specific number of rows with Maximum Sum
- Number of pairs whose sum is a power of 2 in C++
- Minimum and Maximum number of pairs in m teams of n people in C++
- Count pairs with sum as a prime number and less than n in C++
- Maximum Length Chain of Pairs
- Count the number of pairs that have column sum greater than row sum in C++
- Print all pairs with given sum in C++
- Number of pairs with Bitwise OR as Odd number in C++

Advertisements