LeetCode 1877. Minimize Maximum Pair Sum in Array
Intuition
- Pairing the biggest number with the smallest number leads to the minimum pair sum for the biggest number.
- Remove them from the array, find the next biggest and smallest number, and pair them.
- Find the maximum pair sum while pairing and return it after the array is empty.
Approach
- Sort
nums
in ascending order. - Initialise
ans
with 0, which represents that the maximum pair sum innums
is 0. - Iterate over
nums
from 0 tonums.size() / 2 - 1
. - On each iteration:
- Pair
nums[i]
withnums[nums.size()-1-i]
. - Calculate their pair sum and update
ans
.
- Pair
- Return
ans
.
Pseudocode of this problem:
1 | minPairSum(nums): |
Complexity
Time complexity: $O(nlogn)$.
Sorting
nums
in ascending order is $O(nlogn)$.$n / 2$ iterations to pair elements and find the maximum pair sum.
In each iteration:
- Calculate the pair sum and update the maximum pair sum is $O(1)$.
Overall complexity is $O(nlogn)$.
Space complexity: $O(1)$.
Code
1 | class Solution { |