1+ # 1984. Minimum Difference Between Highest and Lowest of K Scores
2+ # Topics: 'Array', 'Sliding Window', 'Sorting'
3+
4+ # 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.
5+
6+ # 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.
7+
8+ # Return the minimum possible difference.
9+
10+
11+
12+ # Example 1:
13+
14+ # Input: nums = [90], k = 1
15+ # Output: 0
16+ # Explanation: There is one way to pick score(s) of one student:
17+ # - [90]. The difference between the highest and lowest score is 90 - 90 = 0.
18+ # The minimum possible difference is 0.
19+
20+ # Example 2:
21+
22+ # Input: nums = [9,4,1,7], k = 2
23+ # Output: 2
24+ # Explanation: There are six ways to pick score(s) of two students:
25+ # - [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
26+ # - [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
27+ # - [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
28+ # - [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
29+ # - [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
30+ # - [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
31+ # The minimum possible difference is 2.
32+
33+
34+
35+ # Constraints:
36+
37+ # 1 <= k <= nums.length <= 1000
38+ # 0 <= nums[i] <= 105
39+
40+ from typing import List
41+
42+ class Solution :
43+ def minimumDifference (self , nums : List [int ], k : int ) -> int :
44+ if len (nums ) <= 1 :
45+ return 0
46+ if k == 1 :
47+ return 0
48+ nums .sort ()
49+ min_diff = nums [k - 1 ]- nums [0 ]
50+ if min_diff == 0 :
51+ return 0
52+ for i in range (k , len (nums ), 1 ):
53+ min_diff = min (min_diff , nums [i ]- nums [i - k + 1 ])
54+ if min_diff == 0 :
55+ return 0
56+ return min_diff
0 commit comments