LeetCode 题解工作台
数组中最大数对和的最小值
一个数对 (a,b) 的 数对和 等于 a + b 。 最大数对和 是一个数对数组中最大的 数对和 。 比方说,如果我们有数对 (1,5) , (2,3) 和 (4,4) , 最大数对和 为 max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 。 给你一个长度为 偶数 n 的…
4
题型
8
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
要使得数组中最大数对和的值最小,那么我们可以将数组中最小的数和最大的数配对,次小的数和次大的数配对,依此类推。 因此,我们可以先对数组进行排序,然后使用两个指针分别指向数组的两端,求出两个指针指向的数的和,更新最大数对和的值,然后将左指针右移一位,右指针左移一位,继续进行操作,直到两个指针相遇为止,即可得到最小的最大数对和。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
一个数对 (a,b) 的 数对和 等于 a + b 。最大数对和 是一个数对数组中最大的 数对和 。
- 比方说,如果我们有数对
(1,5),(2,3)和(4,4),最大数对和 为max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8。
给你一个长度为 偶数 n 的数组 nums ,请你将 nums 中的元素分成 n / 2 个数对,使得:
nums中每个元素 恰好 在 一个 数对中,且- 最大数对和 的值 最小 。
请你在最优数对划分的方案下,返回最小的 最大数对和 。
示例 1:
输入:nums = [3,5,2,3] 输出:7 解释:数组中的元素可以分为数对 (3,3) 和 (5,2) 。 最大数对和为 max(3+3, 5+2) = max(6, 7) = 7 。
示例 2:
输入:nums = [3,5,4,2,4,6] 输出:8 解释:数组中的元素可以分为数对 (3,5),(4,4) 和 (6,2) 。 最大数对和为 max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8 。
提示:
n == nums.length2 <= n <= 105n是 偶数 。1 <= nums[i] <= 105
解题思路
方法一:贪心
要使得数组中最大数对和的值最小,那么我们可以将数组中最小的数和最大的数配对,次小的数和次大的数配对,依此类推。
因此,我们可以先对数组进行排序,然后使用两个指针分别指向数组的两端,求出两个指针指向的数的和,更新最大数对和的值,然后将左指针右移一位,右指针左移一位,继续进行操作,直到两个指针相遇为止,即可得到最小的最大数对和。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def minPairSum(self, nums: List[int]) -> int:
nums.sort()
return max(x + nums[-i - 1] for i, x in enumerate(nums[: len(nums) >> 1]))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of the greedy pairing technique.
- question_mark
Evaluate the candidate's ability to optimize through sorting.
- question_mark
Check if the candidate efficiently handles larger arrays with the two-pointer approach.
常见陷阱
外企场景- error
Failing to sort the array before pairing, leading to suboptimal pairings.
- error
Misunderstanding the importance of balancing the pairs to minimize the maximum sum.
- error
Overcomplicating the problem by attempting to pair elements randomly rather than using a structured approach.
进阶变体
外企场景- arrow_right_alt
Pairing elements with constraints on pair sums.
- arrow_right_alt
Optimizing pair sums for a larger range of values.
- arrow_right_alt
Extending the problem to odd-length arrays with different pairing strategies.