#1877
Minimize Maximum Pair Sum in Array
MediumArrayTwo PointersGreedySortingTwo PointersGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array and pairing the smallest and largest elements, we can minimize the maximum pair sum effectively. This is because pairing extremes balances the sums.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array in non-decreasing order.
- 2Step 2: Initialize a variable to track the maximum pair sum.
- 3Step 3: Pair the first element with the last, the second with the second last, and so on, calculating the sums.
- 4Step 4: Keep track of the maximum sum encountered during the pairing.
solution.py7 lines
1def minimize_max_pair_sum(nums):
2 nums.sort()
3 n = len(nums)
4 max_pair_sum = 0
5 for i in range(n // 2):
6 max_pair_sum = max(max_pair_sum, nums[i] + nums[n - 1 - i])
7 return max_pair_sumℹ
Complexity note: The sorting step dominates the time complexity, while we only use a constant amount of extra space.
- 1Pairing the smallest and largest elements minimizes the maximum sum.
- 2Sorting the array is a crucial step to achieve optimal pairing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.