Problem Description
Given an even-length array nums, pair up its elements such that each element is used in exactly one pair and the maximum pair sum (i.e. the largest sum of any pair) is minimized. The problem asks to return this minimized maximum pair sum.
Key Insights
- Sorting the array allows for pairing the smallest element with the largest element.
- Pairing the lowest with the highest balances the pair sums, thereby minimizing the maximum sum.
- A two-pointer approach (one pointer at the start and one at the end) efficiently forms the optimal pairs.
- This greedy technique ensures each pair's sum is as balanced as possible.
Space and Time Complexity
Time Complexity: O(n log n) – due to the sorting step.
Space Complexity: O(1) if sorted in place (or O(n) if extra space is used).
Solution
The algorithm starts by sorting the array. Then, it pairs the smallest element with the largest element, the second smallest with the second largest, and so on. This minimizes the possibility of any one pair having an excessively high sum, as each large element is counterbalanced by a small element. A simple iteration over the first half of the sorted array using two pointers gives the maximum pair sum among these optimal pairs, which is then returned as the result.