MediumSortingTwo PointersGreedy

Minimize Maximum Pair Sum in Array

1 approach, code in every language

Problem description

You are given an array with an even number of elements, and you must split every element into pairs so that each element belongs to exactly one pair. For any pairing, its cost is the largest sum found among all of its pairs. Different pairings can produce different largest sums.

Return the smallest possible value of that largest pair sum over all valid ways to pair the array. The intuition is to keep big values away from other big values by matching the largest element with the smallest, the second largest with the second smallest, and so on.

Example 1

Input: nums = [3,5,2,3]

Output: 7

Sorted the array is [2,3,3,5]. Pairing 2 with 5 and 3 with 3 gives sums 7 and 6, so the maximum is 7, and no pairing beats it.

Example 2

Input: nums = [3,5,4,2,4,6]

Output: 8

Sorted the array is [2,3,4,4,5,6]. The mirror pairs (2,6), (3,5), (4,4) all sum to 8, giving a maximum pair sum of 8.

Constraints

  • n == nums.length
  • 2 <= n <= 10^5
  • n is even
  • 1 <= nums[i] <= 10^5

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free