NeetCode #222LC-1984EasySliding Window
← Back to All Problems#222 · #1984 · Minimum Difference Between Highest and Lowest of K Scores(学生分数的最小差值)
📌 Problem Statement & Constraints
You are given a 0-indexed integer array
scores and an integer k. Choose k scores so that the difference between the highest and lowest chosen scores is minimised. Return that minimum difference. Constraints: 1 <= k <= scores.length <= 1000, 0 <= scores[i] <= 10^5.💡 Core Algorithmic Approaches
- Sort the scores. In an optimal selection, the
kchosen scores are consecutive in sorted order. - Therefore the answer is the minimum of
scores[i + k - 1] - scores[i]over all validi. - Sorting makes this O(n log n) with an O(n) scan.
- Choosing non-consecutive values can only increase the spread, so the consecutive-window enumeration is exhaustive.
💻 Benchmark Python3 Implementation
class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log n): the sort dominates.
💾 Space Complexity
O(1) beyond the sort.
⚠️ Interview Pitfalls & Follow-ups
- Comparing all subsets of size k: combinatorial explosion.
- Using
scores[i+k] - scores[i]: the window ofkelements spans indicesitoi + k - 1. - Forgetting the
k == 1case: the difference is 0, and the formula givesscores[i] - scores[i] = 0correctly. - Assuming the answer is
scores[-1] - scores[0]: that uses all scores, not exactlyk.