LeetCode 题解工作台
数组拆分
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) ,使得从 1 到 n 的 min(a i , b i ) 总和最大。 返回该 最大总和 。 示例 1: 输入: nums = …
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
对于一个数对 $(a, b)$,我们不妨设 $a \leq b$,那么 $\min(a, b) = a$。为了使得总和尽可能大,我们取的 应该与 尽可能接近,这样可以保留更大的数。 因此,我们可以对数组 进行排序,然后将相邻的两个数分为一组,取每组的第一个数相加即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和最大。
返回该 最大总和 。
示例 1:
输入:nums = [1,4,3,2] 输出:4 解释:所有可能的分法(忽略元素顺序)为: 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 所以最大总和为 4
示例 2:
输入:nums = [6,2,6,5,1,2] 输出:9 解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9
提示:
1 <= n <= 104nums.length == 2 * n-104 <= nums[i] <= 104
解题思路
方法一:排序
对于一个数对 ,我们不妨设 ,那么 。为了使得总和尽可能大,我们取的 应该与 尽可能接近,这样可以保留更大的数。
因此,我们可以对数组 进行排序,然后将相邻的两个数分为一组,取每组的第一个数相加即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about greedy strategy versus brute force to test understanding of invariant validation.
- question_mark
Expect reasoning on why pairing sorted consecutive elements maximizes the sum of minimums.
- question_mark
Look for discussion of time-space trade-offs, such as using counting sort for bounded integer arrays.
常见陷阱
外企场景- error
Attempting all possible pair combinations leads to exponential time complexity.
- error
Pairing without sorting may violate the greedy invariant and produce suboptimal sums.
- error
Misunderstanding that the sum of maximums in each pair is not the goal; the minimums drive the result.
进阶变体
外企场景- arrow_right_alt
Compute the maximum sum if elements can be negative and positive, emphasizing the same greedy principle.
- arrow_right_alt
Adapt the problem to k-sized groups instead of pairs, testing generalization of invariant reasoning.
- arrow_right_alt
Determine the minimum sum of maximums of pairs, which flips the greedy selection logic.