Minimize Maximum Pair Sum in Array

medium two pointers sorting greedy

Problem

You are given an array nums of even length n. Split its elements into exactly n/2 pairs so that every element belongs to exactly one pair. The pair sum of a pair (a, b) is a + b, and the maximum pair sum of a pairing is the largest pair sum among its n/2 pairs.

Choose the pairing so that this maximum pair sum is as small as possible, and return that minimized value.

Inputnums = [3,5,4,2,4,6]
Output8
Sorting gives [2,3,4,4,5,6]; pairing the ends inward yields sums 2+6=8, 3+5=8, 4+4=8, so the largest pair sum is 8 and no pairing does better.

def min_pair_sum(nums):
    nums.sort()
    i, j = 0, len(nums) - 1
    best = 0
    while i < j:
        s = nums[i] + nums[j]
        best = max(best, s)
        i += 1
        j -= 1
    return best
function minPairSum(nums) {
  nums.sort((a, b) => a - b);
  let i = 0, j = nums.length - 1;
  let best = 0;
  while (i < j) {
    const s = nums[i] + nums[j];
    best = Math.max(best, s);
    i++;
    j--;
  }
  return best;
}
int minPairSum(int[] nums) {
    Arrays.sort(nums);
    int i = 0, j = nums.length - 1;
    int best = 0;
    while (i < j) {
        int s = nums[i] + nums[j];
        best = Math.max(best, s);
        i++;
        j--;
    }
    return best;
}
int minPairSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int i = 0, j = nums.size() - 1;
    int best = 0;
    while (i < j) {
        int s = nums[i] + nums[j];
        best = max(best, s);
        i++;
        j--;
    }
    return best;
}
Time: O(n log n) Space: O(log n)