1984. Minimum Difference Between Highest and Lowest of K Scores
Description
You are given a 0-indexed integer array nums
, where nums[i]
represents the score of the ith
student. You are also given an integer k
.
Pick the scores of any k
students from the array so that the difference between the highest and the lowest of the k
scores is minimized.
Return the minimum possible difference.
Example 1:
Input: nums = [90], k = 1 Output: 0 Explanation: There is one way to pick score(s) of one student: - [90]. The difference between the highest and lowest score is 90 - 90 = 0. The minimum possible difference is 0.
Example 2:
Input: nums = [9,4,1,7], k = 2 Output: 2 Explanation: There are six ways to pick score(s) of two students: - [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5. - [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8. - [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2. - [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3. - [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3. - [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6. The minimum possible difference is 2.
Constraints:
1 <= k <= nums.length <= 1000
0 <= nums[i] <= 105
Solutions
Solution 1: Sorting + Sliding Window
We can sort the students' scores in ascending order, then use a sliding window of size $k$ to calculate the difference between the maximum and minimum values in the window, and finally take the minimum of the differences of all windows.
Why do we take the scores of $k$ consecutive students? Because if they are not consecutive, the difference between the maximum and minimum values may remain the same or increase, but it will definitely not decrease. Therefore, we only need to consider the scores of $k$ consecutive students after sorting.
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the number of students.
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|