Minimum Difference Between Highest and Lowest of K Scores - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [9,4,1,7], k = 3
Output: 5
💡 Note: After sorting: [1,4,7,9]. Check windows: [1,4,7] has difference 7-1=6, [4,7,9] has difference 9-4=5. Minimum is 5.
Example 2 — All Elements
$ Input: nums = [90], k = 1
Output: 0
💡 Note: When k=1, we select only one student, so the difference between highest and lowest is 0.
Example 3 — Large Range
$ Input: nums = [41,56,58,75,88], k = 3
Output: 17
💡 Note: Already sorted. Windows: [41,56,58] diff=17, [56,58,75] diff=19, [58,75,88] diff=30. Minimum is 17.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Difference Between Highest and Lowest of K Scores INPUT Original Array: nums 9 i=0 4 i=1 1 i=2 7 i=3 Input Values nums = [9, 4, 1, 7] k = 3 Pick k=3 students with minimum score difference ALGORITHM STEPS 1 Sort the Array [1, 4, 7, 9] 1 4 7 9 2 Sliding Window (k=3) Check consecutive k elements 3 Calculate Differences nums[i+k-1] - nums[i] [1,4,7]: 7-1=6 [4,7,9]: 9-4=5 MIN 4 Return Minimum min(6, 5) = 5 FINAL RESULT Optimal Selection: 4 7 9 Highest: 9, Lowest: 4 Difference: 9 - 4 = 5 OUTPUT 5 OK - Verified! Minimum difference = 5 Key Insight: After sorting, the k students with minimum difference must be consecutive in the sorted array. Use a sliding window of size k to find the minimum difference between first and last elements. Time: O(n log n) for sorting | Space: O(1) extra space TutorialsPoint - Minimum Difference Between Highest and Lowest of K Scores | Optimal Solution
Asked in
Amazon 8 Google 5
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen