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.
- For example, if we have pairs
(1,5),(2,3), and(4,4), the maximum pair sum would bemax(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:
- Each element of
numsis in exactly one pair, and - The maximum pair sum is minimized.
Return 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.
Constraints:
n == nums.length2 <= n <= 105nis even.1 <= nums[i] <= 105
题意:一个数对 (a,b) 的 数对和 等于 a + b 。最大数对和 是一个数对数组中最大的 数对和 。
给你一个长度为 偶数 n 的数组 nums ,请你将 nums 中的元素分成 n / 2 个数对,在最优数对划分的方案下,返回最小的 最大数对和 。
解法 贪心+排序
从小到大排序,最大的元素和最小的元素匹配,依次配对形成数对,返回最大的数对和即可。
class Solution {
public:
int minPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
for (int lo = 0, hi = nums.size() - 1; lo < hi; ++lo, --hi) ans = max(ans, nums[lo] + nums[hi]);
return ans;
}
};
运行效率如下:
执行用时:244 ms, 在所有 C++ 提交中击败了92.02% 的用户
内存消耗:94 MB, 在所有 C++ 提交中击败了75.19% 的用户

博客围绕数组元素配对问题展开,给定偶数长度数组,需将元素分成数对,使最大数对和最小。采用贪心加排序的解法,将数组从小到大排序,最大与最小元素依次配对,最后返回最大数对和。
1937

被折叠的 条评论
为什么被折叠?



