

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Find the largest pair sum in an unsorted array in C++
In this problem, we are given an arr[] consisting of N unsorted elements. Our task is to find the largest pair sum in an unsorted array.
We will find a pair whose sum is the maximum.
Let's take an example to understand the problem,
Input : arr[] = {7, 3, 9, 12, 1} Output : 21
Explanation −
Pair with largest sum, (9, 12). Sum = 21
Solution Approach
A simple solution to the problem is by making a pair of maximum and second maximum elements of the array.
For this we will initialise the max and secondMax elements of the array with the first and second element of the array, greater one is max and other one is secondMax.
Now, loop through the array from index 2 to (n-1). And compare them with max and secondMax values.
If arr[i] is greater than max, secondMax = max and max = arr[i].
If arr[i] is greater than secondMax, secondMax = arr[i].
And at the end of the loop, return the (max + secondMax).
Example
Program to illustrate the working of our solution
#include<iostream> using namespace std; int findPairLargestSum(int arr[], int n){ int max, secondMax; if (arr[0] > arr[1]){ max = arr[0]; secondMax = arr[1]; } else{ max = arr[1]; secondMax = arr[0]; } for (int i = 2; i<n; i ++){ if (arr[i] > max){ secondMax = max; max = arr[i]; } else if (arr[i] > secondMax && arr[i] != max) secondMax = arr[i]; } return (max + secondMax); } int main(){ int arr[] = {12, 34, 10, 6, 40}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"The sum of elements of pair with max sum is "<<findPairLargestSum(arr, n); return 0; }
Output
The sum of elements of pair with max sum is 74
- Related Questions & Answers
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- Find k closest numbers in an unsorted array in C++
- Print all pairs in an unsorted array with equal sum in C++
- Find floor and ceil in an unsorted array using C++.
- K’th Smallest/Largest Element in Unsorted Array in C++
- kth smallest/largest in a small range unsorted array in C++
- Find the largest three elements in an array in C++
- Pair whose sum exists in the array in JavaScript
- Java program to find the largest number in an array
- Python Program to find the largest element in an array
- Find start and ending index of an element in an unsorted array in C++
- Split Array Largest Sum in C++
- Find pair with maximum GCD in an array in C++
- Java program to find the 3rd largest number in an array
- Java program to find the 2nd largest number in an array