The pair sum of a pair (a,b)
is equal to a + b
. The maximum pair sum is the largest pair sum in a list of pairs.
(1,5)
, (2,3)
, and (4,4)
, the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.Given an array nums
of even length n
, pair up the elements of nums
into n / 2
pairs such that:
nums
is in exactly one pair, andReturn the minimized maximum pair sum after optimally pairing up the elements.
Example 1:
Input: nums = [3,5,2,3]
Output: 7
Explanation: The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
Example 2:
Input: nums = [3,5,4,2,4,6]
Output: 8
Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
The problem asks us to pair elements in an array of even length such that the maximum pair sum is minimized. A naive approach would be to try all possible pairings and compute the maximum pair sum for each pairing, then take the minimum of those. However, this would be very inefficient. A better approach is to sort the array and then pair the smallest and largest elements, the second smallest and second largest, and so on. This ensures that the maximum pair sum is minimized.
Optimal Solution
nums
in ascending order.nums[i]
with nums[n - 1 - i]
for i
from 0 to n / 2 - 1
.Code Implementation (Python)
def min_max_pair_sum(nums):
nums.sort()
max_sum = 0
n = len(nums)
for i in range(n // 2):
max_sum = max(max_sum, nums[i] + nums[n - 1 - i])
return max_sum
# Example Usage
nums1 = [3, 5, 2, 3]
print(f"Input: {nums1}, Output: {min_max_pair_sum(nums1)}") # Output: 7
nums2 = [3, 5, 4, 2, 4, 6]
print(f"Input: {nums2}, Output: {min_max_pair_sum(nums2)}") # Output: 8
Code Implementation (Java)
import java.util.Arrays;
class Solution {
public int minMaxPairSum(int[] nums) {
Arrays.sort(nums);
int maxSum = 0;
int n = nums.length;
for (int i = 0; i < n / 2; i++) {
maxSum = Math.max(maxSum, nums[i] + nums[n - 1 - i]);
}
return maxSum;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = {3, 5, 2, 3};
System.out.println("Input: {3, 5, 2, 3}, Output: " + solution.minMaxPairSum(nums1)); // Output: 7
int[] nums2 = {3, 5, 4, 2, 4, 6};
System.out.println("Input: {3, 5, 4, 2, 4, 6}, Output: " + solution.minMaxPairSum(nums2)); // Output: 8
}
}
Big(O) Run-time Analysis
n / 2
times, performing constant-time operations (addition and comparison) in each iteration. This part takes O(n) time.Big(O) Space Usage Analysis
Edge Cases
n >= 2
, so an empty array is not a valid input. However, if we were to handle it, we would need to raise an exception or return a default value.n = 10^5
), the O(n log n) time complexity might become a concern. However, since n
is limited to 10^5
, the algorithm should still run efficiently.