1877. Minimize Maximum Pair Sum in Array【贪心/排序】

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

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 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:

  • Each element of nums is 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.length
  • 2 <= n <= 105
  • n is 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% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值