Find the largest pair sum in an unsorted array in C++

C++Server Side ProgrammingProgramming

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
raja
Updated on 28-Jan-2022 11:32:16

Advertisements