![]() |
VOOZH | about |
Given an unsorted array arr[] of distinct integers, find the largest pair sum in it. If there are less than 2 elements, then we need to return -1.
Input : arr[] = [12, 34, 10, 6, 40]
Output : 74
Explanation : The two largest elements are40and34. Their sum is74.Input : arr[] = [10, 10, 10]
Output : 20
Explanation : Any two10's give the maximum sum.Input arr[] = [10]
Output : -1
Explanation : At least two elements are required to form a pair.
Table of Content
The idea is to use two nested loops to iterate over all possible pairs of integers in the array, compute their sum and keep track of the maximum sum encountered so far.
Max Pair Sum is 74
The largest pair sum in an array is always formed by the largest and second-largest elements. Instead of checking all possible pairs, we traverse the array once and keep track of these two values. Whenever a larger element is found, we update the largest and second-largest accordingly. Finally, their sum gives the required maximum pair sum.
Max Pair Sum is 74