leetcode - 1877. Minimize Maximum Pair Sum in Array

Description

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 <= 10^5
n is even.
1 <= nums[i] <= 10^5

Solution

The minimum pair sum should be the current minimum number and the maximum number, so sort the list, pair up the minimum number and the maximum number.

Time complexity: o ( n log ⁡ n ) o(n \log n) o(nlogn)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def minPairSum(self, nums: List[int]) -> int:
        res = 0
        nums.sort()
        n = len(nums)
        for i in range(n):
            if i >= n // 2:
                break
            cur_pair_sum = nums[i] + nums[n - i - 1]
            res = max(cur_pair_sum, res)
        return res
相关推荐
Xの哲學29 分钟前
Perf使用详解
linux·网络·网络协议·算法·架构
奶黄小甜包34 分钟前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
想不明白的过度思考者39 分钟前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
小七rrrrr1 小时前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
code小毛孩1 小时前
leetcodehot100 矩阵置零
算法
一支闲人1 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
何妨重温wdys1 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
姜不吃葱1 小时前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100
PineappleCoder1 小时前
大小写 + 标点全搞定!JS 如何精准统计单词频率?
前端·javascript·算法
zzx_blog1 小时前
简单易懂的leetcode 100题-第三篇 移动0,颜色分类,数组中的第K个最大元素
leetcode·面试