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 K ScoresFind k students with most similar scoresInput Scores9417k = 3 students neededSORTSorted Scores1479Sliding Window of Size k=3Window 1: [1,4,7]147Difference: 7 - 1 = 6Window 2: [4,7,9]479Difference: 9 - 4 = 5Choose minimum: min(6, 5) = 5Answer: 5
Understanding the Visualization
1
Input
Array of student scores and k value
2
Sort
Sort scores to group similar values together
3
Window
Find k consecutive scores with minimum range
Key Takeaway
🎯 Key Insight: After sorting, the optimal k students are always consecutive in the array
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