NeetCode #280LC-2616MediumBinary Search
← Back to All Problems#280 · #2616 · Minimize the Maximum Difference of Pairs(最小化数对的最大差值)
📌 Problem Statement & Constraints
You are given a 0-indexed integer array
nums and an integer p. Find p pairs of indices such that no index appears in more than one pair, minimising the maximum difference among the pairs. Return that minimum possible maximum difference. Constraints: 1 <= nums.length <= 10^5, 0 <= nums[i] <= 10^9, 0 <= p <= nums.length / 2.💡 Core Algorithmic Approaches
- Binary search on the maximum allowed difference
d: "can we form at leastppairs with difference at mostd" is monotone. - Sort the array. For a given
d, greedily pair adjacent elements whenever their difference is at mostd, skipping two positions on a match. - The greedy is optimal for maximising the number of pairs under a difference cap, because sorting makes the best partner for each element its immediate neighbour.
- Use the upper-biased midpoint to find the smallest feasible
d.
💻 Benchmark Python3 Implementation
class Solution:
def minimizeMax(self, nums: List[int], p: int) -> int:
nums.sort()
def pairs_within(limit: int) -> int:
cnt = 0
i = 0
while i < len(nums) - 1:
if nums[i + 1] - nums[i] <= limit:
cnt += 1
i += 2 # both used
else:
i += 1
return cnt
lo, hi = 0, nums[-1] - nums[0]
while lo < hi:
mid = (lo + hi) // 2
if pairs_within(mid) >= p:
hi = mid # feasible -> try a smaller limit
else:
lo = mid + 1
return lo⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log n + n log(max difference)): the sort plus O(log V) greedy passes.
💾 Space Complexity
O(1) beyond the sort.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting to sort: the greedy pairing relies on adjacent elements being the closest available.
- Using
hi = mid - 1when feasible: could skip the optimum. - Pairing non-adjacent elements greedily: after sorting, pairing adjacent elements is optimal for maximising the count.
- Handling
p == 0: the answer is 0, which the initiallo = 0gives directly.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
最小化数对的最大差值
给你一个下标从 0 开始的整数数组 nums 和一个整数 p。请你从 nums 中找出 p 个 互不相同 的下标,并将它们配对。定义一对下标的 差值 为两个下标对应元素的 绝对差 。请你返回在 p 对数对中,数对差值的 最大值 的 最小可能值 。约束:1 ≤ nums.length ≤ 10^5;0 ≤ nums[i] ≤ 10^9;1 ≤ p ≤ nums.length / 2。
核心要点
- 排序 + 二分答案 + 贪心判定(标准解) :先排序(相邻元素的差值最小,因此最优配对一定在相邻元素之间)。
- 二分「最大差值上限 d」 ,判定「能否选出至少 p 对,使每对的差 ≤ d」。
- 贪心判定 :从左到右扫描,若 nums[i+1] − nums[i] <= d 则配对成功并 i += 2 ,否则 i += 1 。
- 为什么贪心最优 :能配对就配对(并且跳过两个元素)可以得到最多对数,这是「不相邻选择」的经典贪心。
- 答案范围 : [0, nums[-1] − nums[0]] 。
常见陷阱
- 不排序 :不相邻的元素配对会产生更大的差值,最优配对必然在排序后的相邻元素之间。
- p == 0 时未特判 :此时答案应为 0,但二分区间 [0, nums[-1]−nums[0]] 在数组长度为 1 时也成立;显式特判更安全。
- 判定函数中 i += 2 写成 i += 1 :会导致元素被重复使用,配对对数被高估。
- 用 DP 求解 : dp[i][j] 表示前 i 个元素配 j 对的最小最大差,复杂度 O(n · p),p 可达 n/2,总 O(n²) 会超时。
- 二分上界写成 10^9 :虽然正确但二分次数更多;取 nums[-1] − nums[0] 更紧。
参考实现
class Solution:
def minimizeMax(self, nums: list[int], p: int) -> int:
if p == 0:
return 0
nums.sort()
def can_form(d: int) -> bool:
"""能否选出至少 p 对,每对差值 <= d。"""
cnt = 0
i = 0
n = len(nums)
while i < n - 1:
if nums[i + 1] - nums[i] <= d:
cnt += 1
i += 2 # 配对成功,跳过两个元素
else:
i += 1
return cnt >= p
l, r = 0, nums[-1] - nums[0]
while l < r:
mid = (l + r) // 2
if can_form(mid):
r = mid # 可行 -> 尝试更小的上限
else:
l = mid + 1
return l