Minimum Difference Between Highest and Lowest of K Scores (LeetCode 1984): Solution and Explanation
Pick k scores so that the highest minus the lowest is as small as possible. After sorting, the best pick is always k neighbouring scores, so one pass over windows of size k finds the answer.
Intuition
The spread of a pick depends only on its lowest and highest score. Whatever sits in between costs nothing.
Sort the scores and imagine them as dots on a number line. If a pick of k skips a dot that lies between its lowest and highest, swapping that dot in for one of the ends can only shrink the spread or keep it the same.
So the optimal pick is k consecutive dots in sorted order. There are only n - k + 1 such windows, and the spread of the window starting at i is nums[i + k - 1] - nums[i].
Approach: Sort + fixed-size sliding window
- Sort
numsin ascending order. - Start
bestat the full spreadnums[n - 1] - nums[0], an upper bound for any pick. - For every start
ifrom0ton - k, setbest = min(best, nums[i + k - 1] - nums[i]). - Return
best.
Step-by-step example
nums = [9,4,1,7], k = 2
- Sort: [1,4,7,9]. Start best = 9 - 1 = 8.
- Window [1,4]: spread 3, best = 3.
- Window [4,7]: spread 3, best stays 3.
- Window [7,9]: spread 2, best = 2.
- The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def minimumDifference(self, nums: List[int], k: int) -> int:
3 nums.sort()
4 best = nums[-1] - nums[0]
5 for i in range(len(nums) - k + 1):
6 best = min(best, nums[i + k - 1] - nums[i])
7 return best1class Solution {
2 public int minimumDifference(int[] nums, int k) {
3 Arrays.sort(nums);
4 int best = nums[nums.length - 1] - nums[0];
5 for (int i = 0; i + k - 1 < nums.length; i++) {
6 best = Math.min(best, nums[i + k - 1] - nums[i]);
7 }
8 return best;
9 }
10}1class Solution {
2public:
3 int minimumDifference(vector<int>& nums, int k) {
4 sort(nums.begin(), nums.end());
5 int best = nums.back() - nums[0];
6 for (int i = 0; i + k - 1 < (int)nums.size(); i++) {
7 best = min(best, nums[i + k - 1] - nums[i]);
8 }
9 return best;
10 }
11};Time and space complexity
O(n log n)
Sorting costs O(n log n); the window pass is O(n).
O(1)
Only a counter and the best value, apart from the in-place sort.
Other approaches
Brute force over combinations (time O(C(n, k) * k), space O(k))
Try every set of k scores and compute its spread. Correct, but the number of combinations explodes even for modest n.
Counting sort (time O(n + V), space O(V))
Since scores are at most 10^5, bucket them by value instead of comparison sorting, then run the same window. Linear in n plus the value range, rarely worth it at n = 1000.
Common mistakes
- Sliding the window over the unsorted array. Neighbours by index are not neighbours by value.
- Off-by-one in the loop bound: the last window starts at
n - k, so the loop runsn - k + 1times. - Forgetting the k = 1 case: every window has spread 0, so the answer is 0.
- Starting best at 0 instead of a large value, which makes
minreturn 0 for every input.
Frequently asked questions
Why is the best pick always k consecutive sorted scores?
Take any pick with lowest value a and highest value b. Every score between a and b in sorted order could replace a chosen score without moving a or b, so there is a pick of k neighbours with spread at most b - a.
What happens when k equals 1?
A single score is both the highest and the lowest, so every window has spread 0 and the answer is 0.
What is the time and space complexity?
O(n log n) time for sorting and O(1) extra space for the scan.