LeetCode 题解工作台
最小化数对的最大差值
给你一个下标从 0 开始的整数数组 nums 和一个整数 p 。请你从 nums 中找到 p 个下标对,每个下标对对应数值取差值,你需要使得这 p 个差值的 最大值 最小 。同时,你需要确保每个下标在这 p 个下标对中最多出现一次。 对于一个下标对 i 和 j ,这一对的差值为 |nums[i] -…
5
题型
9
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们注意到,最大差值具备单调性,即如果最大差值 满足条件,那么 也一定满足条件。因此我们可以使用二分查找的方法,找到最小的满足条件的最大差值。 我们可以将数组 排序,然后枚举最大差值 ,判断是否存在 个下标对,每个下标对对应数值取差值的最大值不超过 。如果存在,那么我们就可以将 减小,否则我们就将 增大。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 p 。请你从 nums 中找到 p 个下标对,每个下标对对应数值取差值,你需要使得这 p 个差值的 最大值 最小。同时,你需要确保每个下标在这 p 个下标对中最多出现一次。
对于一个下标对 i 和 j ,这一对的差值为 |nums[i] - nums[j]| ,其中 |x| 表示 x 的 绝对值 。
请你返回 p 个下标对对应数值 最大差值 的 最小值 。我们定义空集的最大值为零。
示例 1:
输入:nums = [10,1,2,7,1,3], p = 2 输出:1 解释:第一个下标对选择 1 和 4 ,第二个下标对选择 2 和 5 。 最大差值为 max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1 。所以我们返回 1 。
示例 2:
输入:nums = [4,2,1,2], p = 1 输出:0 解释:选择下标 1 和 3 构成下标对。差值为 |2 - 2| = 0 ,这是最大差值的最小值。
提示:
1 <= nums.length <= 1050 <= nums[i] <= 1090 <= p <= (nums.length)/2
解题思路
方法一:二分查找 + 贪心
我们注意到,最大差值具备单调性,即如果最大差值 满足条件,那么 也一定满足条件。因此我们可以使用二分查找的方法,找到最小的满足条件的最大差值。
我们可以将数组 排序,然后枚举最大差值 ,判断是否存在 个下标对,每个下标对对应数值取差值的最大值不超过 。如果存在,那么我们就可以将 减小,否则我们就将 增大。
判断是否存在 个下标对,每个下标对对应数值取差值的最大值不超过 ,可以使用贪心的方法。我们从左到右遍历数组 ,对于当前遍历到的下标 ,如果 位置的数与 位置的数的差值不超过 ,那么我们就可以将 和 位置的数作为一个下标对,更新下标对的数量 ,然后将 的值增加 。否则,我们就将 的值增加 。遍历结束,如果 的值大于等于 ,那么就说明存在 个下标对,每个下标对对应数值取差值的最大值不超过 ,否则就说明不存在。
时间复杂度 ,其中 是数组 的长度,而 是数组 中的最大值与最小值的差值。空间复杂度 。
class Solution:
def minimizeMax(self, nums: List[int], p: int) -> int:
def check(diff: int) -> bool:
cnt = i = 0
while i < len(nums) - 1:
if nums[i + 1] - nums[i] <= diff:
cnt += 1
i += 2
else:
i += 1
return cnt >= p
nums.sort()
return bisect_left(range(nums[-1] - nums[0] + 1), True, key=check)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \cdot\log V + n \cdot\log n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Ensure the candidate understands how sorting and binary search interact to optimize the solution.
- question_mark
Look for clarity in how the candidate explains the dynamic programming aspect of the problem.
- question_mark
Assess whether the candidate effectively applies greedy strategies in pairing elements.
常见陷阱
外企场景- error
Forgetting to sort the array first, leading to larger differences being considered.
- error
Misunderstanding the binary search logic and not correctly narrowing the possible differences.
- error
Pairing indices in a non-optimal way, leading to suboptimal solutions.
进阶变体
外企场景- arrow_right_alt
Adjusting the value of p to see if a higher or lower number of pairs impacts the result.
- arrow_right_alt
Increasing the size of nums to test for performance and handling larger arrays.
- arrow_right_alt
Changing the constraints to include larger ranges of numbers or different number types.