Open In App

Find the largest pair sum in an unsorted array

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74.
Difficulty Level: Rookie 
 

Brute Force Approach:

Brute force approach to solve this problem would be 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. The time complexity of this approach would be O(n^2).

Below is implementation of the above approach:

C++




// C++ program to find largest pair sum in a given array
#include <bits/stdc++.h>
using namespace std;
 
/* Function to return largest pair sum. Assumes that
there are at-least two elements in arr[] */
int findLargestSumPair(int arr[], int n)
{
    int maxSum = INT_MIN;
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];
            if (sum > maxSum) {
                maxSum = sum;
            }
        }
    }
    return maxSum;
}
 
 
/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 34, 10, 6, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Max Pair Sum is "
        << findLargestSumPair(arr, n);
    return 0;
}


Java




import java.util.*;
 
public class Main
{
 
  /* Function to return largest pair sum. Assumes that
    there are at-least two elements in arr[] */
  static int findLargestSumPair(int[] arr, int n) {
    int maxSum = Integer.MIN_VALUE;
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
        int sum = arr[i] + arr[j];
        if (sum > maxSum) {
          maxSum = sum;
        }
      }
    }
    return maxSum;
  }
 
  /* Driver program to test above function */
  public static void main(String[] args) {
    int[] arr = {12, 34, 10, 6, 40};
    int n = arr.length;
    System.out.println("Max Pair Sum is " + findLargestSumPair(arr, n));
  }
}


Python3




import sys
 
# Function to return largest pair sum. Assumes that
# there are at-least two elements in arr[]
 
 
def findLargestSumPair(arr, n):
    maxSum = -sys.maxsize - 1
    for i in range(0, n - 1):
        for j in range(i + 1, n):
            sum = arr[i] + arr[j]
            if (sum > maxSum):
                maxSum = sum
    return maxSum
 
 
# Driver program to test above function
if __name__ == '__main__':
    arr = [12, 34, 10, 6, 40]
    n = len(arr)
    print("Max Pair Sum is", findLargestSumPair(arr, n))


C#




using System;
 
class Program
{
 
  /* Function to return largest pair sum. Assumes that
    there are at-least two elements in arr[] */
  static int FindLargestSumPair(int[] arr, int n)
  {
    int maxSum = int.MinValue;
    for (int i = 0; i < n - 1; i++)
    {
      for (int j = i + 1; j < n; j++)
      {
        int sum = arr[i] + arr[j];
        if (sum > maxSum)
        {
          maxSum = sum;
        }
      }
    }
    return maxSum;
  }
 
  // Driver code
  static void Main(string[] args)
  {
    int[] arr = { 12, 34, 10, 6, 40 };
    int n = arr.Length;
    Console.WriteLine("Max Pair Sum is " + FindLargestSumPair(arr, n));
  }
}


Javascript




/* Function to return largest pair sum. Assumes that
there are at-least two elements in arr[] */
function findLargestSumPair(arr) {
    let maxSum = Number.MIN_SAFE_INTEGER; // Initialize maxSum to the smallest possible value
     
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            let sum = arr[i] + arr[j]; // Calculate sum of pair (arr[i], arr[j])
             
            if (sum > maxSum) {
                maxSum = sum; // Update maxSum if current sum is greater
            }
        }
    }
    return maxSum;
}
 
/* Driver program to test above function */
let arr = [12, 34, 10, 6, 40];
let maxPairSum = findLargestSumPair(arr);
console.log("Max Pair Sum is " + maxPairSum);


Output

Max Pair Sum is 74

Time Complexity: O(N^2)

Auxiliary Space: O(1)

This problem mainly boils down to finding the largest and second-largest element in an array. We can find the largest and second-largest in O(n) time by traversing the array once. 
 

1) Initialize the 
first = Integer.MIN_VALUE
second = Integer.MIN_VALUE
2) Loop through the elements
a) If the current element is greater than the first max element, then update second max to the first
max and update the first max to the current element.
3) Return (first + second)

Below is the implementation of the above algorithm: 
 

C++




// C++ program to find largest pair sum in a given array
#include <iostream>
using namespace std;
 
/* Function to return largest pair sum. Assumes that
   there are at-least  two elements in arr[] */
int findLargestSumPair(int arr[], int n)
{
    // Initialize first and second largest element
    int first, second;
    if (arr[0] > arr[1]) {
        first = arr[0];
        second = arr[1];
    }
    else {
        first = arr[1];
        second = arr[0];
    }
 
    // Traverse remaining array and find first and second
    // largest elements in overall array
    for (int i = 2; i < n; i++) {
        /* If current element is greater than first then
          update both first and second */
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        }
 
        /* If arr[i] is in between first and second then
         * update second  */
        else if (arr[i] > second && arr[i] != first)
            second = arr[i];
    }
    return (first + second);
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 34, 10, 6, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Max Pair Sum is "
         << findLargestSumPair(arr, n);
    return 0;
}


Java




public class LargestPairSum {
 
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
 
        int arr[] = { 12, 34, 10, 6, 40};
        System.out.println(largestPairSum(arr, arr.length));
    }
 
    private static int largestPairSum(int[] arr, int n)
    {
        int j = 0;
        int max = n == 1 ? arr[0] + arr[1] : arr[0];
        for (int i = 0; i < n; i++) {
            int sum = arr[j] + arr[i];
            if (sum > max) {
                max = sum;
                if (arr[j] < arr[i]) {
                    j = i;
                }
            }
        }
        return max;
    }
}
/**
 * This code is contributed by Tanveer Baba
 */


Python3




# Python3 program to find largest
# pair sum in a given array
 
# Function to return largest pair
# sum. Assumes that there are
# at-least two elements in arr[]
 
 
def findLargestSumPair(arr, n):
 
    # Initialize first and second
    # largest element
    if arr[0] > arr[1]:
        first = arr[0]
        second = arr[1]
 
    else:
        first = arr[1]
        second = arr[0]
 
    # Traverse remaining array and
    # find first and second largest
    # elements in overall array
    for i in range(2, n):
 
        # If current element is greater
        # than first then update both
        # first and second
        if arr[i] > first:
            second = first
            first = arr[i]
 
        # If arr[i] is in between first
        # and second then update second
        elif arr[i] > second and arr[i] != first:
            second = arr[i]
 
    return (first + second)
 
 
# Driver program to test above function */
arr = [12, 34, 10, 6, 40]
n = len(arr)
print("Max Pair Sum is",
      findLargestSumPair(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal


C#




// C# program to find largest
// pair sum in a given array
using System;
 
class GFG {
    /* Method to return largest pair
    sum. Assumes that there are
    at-least two elements in arr[] */
    static int findLargestSumPair(int[] arr)
    {
        // Initialize first and
        // second largest element
        int first, second;
        if (arr[0] > arr[1]) {
            first = arr[0];
            second = arr[1];
        }
        else {
            first = arr[1];
            second = arr[0];
        }
 
        // Traverse remaining array and
        // find first and second largest
        // elements in overall array
        for (int i = 2; i < arr.Length; i++) {
            /* If current element is greater
               than first then update both
               first and second */
            if (arr[i] > first) {
                second = first;
                first = arr[i];
            }
 
            /* If arr[i] is in between first
               and second then update second */
            else if (arr[i] > second && arr[i] != first)
                second = arr[i];
        }
        return (first + second);
    }
    // Driver Code
    public static void Main()
    {
        int[] arr1 = new int[] { 12, 34, 10, 6, 40 };
        Console.Write("Max Pair Sum is "
                      + findLargestSumPair(arr1));
    }
}


Javascript




<script>
 
    // Javascript program to find largest
    // pair sum in a given array
     
    /* Method to return largest pair
    sum. Assumes that there are
    at-least two elements in arr[] */
    function findLargestSumPair(arr)
    {
        // Initialize first and
        // second largest element
        let first, second;
        if (arr[0] > arr[1])
        {
            first = arr[0];
            second = arr[1];
        }
        else
        {
            first = arr[1];
            second = arr[0];
        }
       
        // Traverse remaining array and
        // find first and second largest
        // elements in overall array
        for (let i = 2; i < arr.length; i ++)
        {
            /* If current element is greater
               than first then update both
               first and second */
            if (arr[i] > first)
            {
                second = first;
                first = arr[i];
            }
       
            /* If arr[i] is in between first
               and second then update second */
            else if (arr[i] > second &&
                     arr[i] != first)
                second = arr[i];
        }
        return (first + second);
    }
       
    let arr1 = [12, 34, 10, 6, 40];
    document.write("Max Pair Sum is " + findLargestSumPair(arr1));
     
    // This code is contributed by divyeshrabadiy07.
</script>


PHP




<?php
// PHP program to find largest
// pair sum in a given array
 
// Function to return largest
// pair sum. Assumes that
// there are at-least two
// elements in arr[] */
function findLargestSumPair($arr, $n)
{
     
    // Initialize first and
    // second largest element
    $first;
    $second;
     
    if ($arr[0] > $arr[1])
    {
        $first = $arr[0];
        $second = $arr[1];
    }
    else
    {
        $first = $arr[1];
        $second = $arr[0];
    }
 
    // Traverse remaining array
    // and find first and second
    // largest elements in overall
    // array
    for ( $i = 2; $i<$n; $i ++)
    {
         
        // If current element is greater
        // than first then update both
        // first and second
        if ($arr[$i] > $first)
        {
            $second = $first;
            $first = $arr[$i];
        }
 
        // If arr[i] is in between first
        // and second then update second
        else if ($arr[$i] > $second and
                 $arr[$i] != $first)
            $second = $arr[$i];
    }
    return ($first + $second);
}
 
    // Driver Code
    $arr = array(12, 34, 10, 6, 40);
    $n = count($arr);
    echo "Max Pair Sum is "
          , findLargestSumPair($arr, $n);
 
// This code is contributed by anuj_67.
?>


Output

Max Pair Sum is 74

The time complexity of the above solution is O(n).
The space complexity of the above solution is O(1).


 



Previous Article
Next Article

Similar Reads

Find largest positive integer x missing from unsorted array such that min(arr[]) &lt; x &lt; max(arr[])
Given an array arr[] containing integers. The task is to find the largest positive integer x missing from the array such that min(arr[]) &lt; x &lt; max(arr[]). Examples Input: arr[] = {2, 3, 7, 6, 8}Output: 5Explanation: 5 is the largest positive integer missing from arr[] and 2 &lt; 5 &lt; 8. Input: arr[] = { 2, 3, -7, 1, 4 }Output: -1 Naive Appr
9 min read
kth smallest/largest in a small range unsorted array
Find kth smallest or largest element in an unsorted array, where k&lt;=size of array. It is given that elements of array are in small range. Examples: Input : arr[] = {3, 2, 9, 5, 7, 11, 13} k = 5 Output: 9 Input : arr[] = {16, 8, 9, 21, 43} k = 3 Output: 16 Input : arr[] = {50, 50, 40} k = 2 Output: 50 As the given array elements are in a small ra
5 min read
Kth smallest or largest element in unsorted Array using Counting Sort
Given an array arr[] and a number K, where K is smaller than the size of the array, we need to find the Kth smallest element in the given array. It is given that array elements can be repeated (not limited to distinct). Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 1, 5, 4, 20, 15, 8}, K = 5 Output: 8 We have di
7 min read
K’th Smallest/Largest Element in Unsorted Array | Expected Linear Time
Prerequisite: K’th Smallest/Largest Element in Unsorted Array | Set 1 Given an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is given that all array elements are distinct. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3Output: 7 Input: arr[] = {7, 10, 4, 3,
13 min read
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Given an array and a number k where k is smaller than the size of the array, we need to find the k’th largest element in the given array. It is given that all array elements are distinct. We recommend reading the following post as a prerequisite to this post. K’th Smallest/Largest Element in Unsorted Array | Set 1 Examples: Input: arr[] = {7, 10, 4
9 min read
K’th Smallest/Largest Element in Unsorted Array | Worst case Linear Time
We recommend reading the following posts as a prerequisite for this post.K’th Smallest/Largest Element in Unsorted Array K’th Smallest/Largest Element in Unsorted Array | Expected Linear TimeGiven an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is given that all
15+ min read
K’th Smallest/Largest Element in Unsorted Array
Given an array arr[] of size N and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Given that all array elements are distinct. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 K'th smallest element in an unsorted array
15+ min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] &gt; B[i] + B[j] and i &lt; j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
15+ min read
Find the largest contiguous pair sum in given Array
Given an integer array arr[] of size N, the task is to find contiguous pair {a, b} such that sum of both elements in the pair is maximum. If there are more than one such pairs with maximum sum then print any of such pair. In the case of multiple pairs with the largest sum, print any one of them.Examples: Input: arr[] = {1, 2, 3, 4} Output: 3 4 Expl
6 min read
Smallest Difference pair of values between two unsorted Arrays
Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference. Examples : Input : A[] = {1, 3, 15, 11, 2} B[] = {23, 127, 235, 19, 8} Output : 3 That is, the pair (11, 8) Input : A[] = {10, 5, 40} B[] = {50, 90, 80} Output : 10That is, the pair (40, 50)Brute For
11 min read
Article Tags :
Practice Tags :