869923. Largest Pair Sum

Easy

Largest Pair Sum

Slug: pair-sum--120604

Difficulty: Easy

Id: 869923

Topic Tags: two-pointer-algorithm, Arrays, Searching

Company Tags: None

Summary

Given an array of integers, the task is to find the largest pair sum possible by choosing any two elements from the given array. This problem involves searching and sorting techniques.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates through the array once. We maintain two pointers, one at the start of the array and one at the end. At each step, we compare the values at these positions and update our pair sum accordingly.

Here's the step-by-step breakdown:

  1. Initialize two pointers, start and end, to the first and last elements of the array respectively.
  2. Compare the values at start and end.
  3. If start is smaller than end, update pair_sum with the sum of these two values and move start one step forward.
  4. If end is smaller than start, update pair_sum with the sum of these two values and move end one step backward.
  5. Repeat steps 2-4 until start meets or crosses end.
  6. The final value of pair_sum is the largest possible pair sum.

The time complexity of this algorithm is O(n), where n is the size of the input array, as we only need to iterate through the array once. The space complexity is O(1) since we're not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public int largestPairSum(int[] arr) {
    if (arr.length < 2) return -1; // edge case

    int start = 0, end = arr.length - 1;
    int pair_sum = Integer.MIN_VALUE;

    while (start <= end) {
        if (arr[start] > arr[end]) {
            pair_sum = Math.max(pair_sum, arr[start] + arr[end]);
            start++;
        } else {
            pair_sum = Math.max(pair_sum, arr[start] + arr[end]);
            end--;
        }
    }

    return pair_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.