Minimize Maximum Pair Sum in Array (LeetCode 1877): Solution and Explanation

Medium
Array
Two Pointers
Greedy
Sorting

Split an even-length array into pairs so the largest pair sum is as small as possible, and return that value.

Intuition

The largest value has to sit in some pair. Its pair sum is smallest when its partner is the smallest value, so that pairing is never a mistake.

Remove those two and the same argument applies to what is left: the next largest should pair with the next smallest.

After sorting, this is a two-pointer walk from both ends toward the middle, and the answer is the biggest sum seen on the way.

Approach: Sort, then pair the ends

  1. Sort nums in ascending order.
  2. Set i = 0, j = n - 1, and best = 0.
  3. While i < j, update best = max(best, nums[i] + nums[j]), then move i right and j left.
  4. Return best.

Step-by-step example

nums = [3,5,4,2,4,6]
  1. Sort: [2,3,4,4,5,6].
  2. Pair 2 with 6: sum 8, best = 8.
  3. Pair 3 with 5: sum 8, best stays 8.
  4. Pair 4 with 4: sum 8, best stays 8.
  5. Return 8.

Code: Python, Java, C++

1class Solution:
2    def minPairSum(self, nums: List[int]) -> int:
3        nums.sort()
4        best = 0
5        i, j = 0, len(nums) - 1
6        while i < j:
7            best = max(best, nums[i] + nums[j])
8            i += 1
9            j -= 1
10        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort O(n + V)
Sort, then pair the ends O(n log n)
Try every pairing O(n!)
Time

O(n log n)

Sorting dominates; the pairing pass is O(n).

Space

O(1)

Only the two pointers and the running maximum, beyond whatever the sort uses.

Other approaches

Counting sort (time O(n + V), space O(V))

Values are at most 10^5, so count each value and walk the counts from both ends. This removes the log factor.

Try every pairing (time O(n!), space O(n))

Enumerate all perfect matchings and take the best maximum. Correct but exponential, useful only to check small cases.

Common mistakes

  • Pairing adjacent values after sorting, which pushes the two largest values into one pair.
  • Returning the minimum pair sum instead of the maximum.
  • Forgetting to sort first; the end-pairing only works on sorted data.

Frequently asked questions

Why is pairing smallest with largest optimal?

Take any optimal pairing where the largest value L is not with the smallest value S. Swapping partners so that L pairs with S and their old partners pair together never increases the maximum, so an optimal answer with L and S together always exists.

Can the sum overflow?

No. Each value is at most 10^5, so a pair sum is at most 2 * 10^5, well within a 32-bit int.

Is this related to Boats to Save People?

Yes. Both sort and pair the lightest remaining item with the heaviest, but Boats lets a heavy person ride alone, while here every element must be paired.