Choose any group of k scores and minimize the spread between the largest and smallest score in that group.
Problem
You are given an array of student scores and an integer k. Your task is to select exactly k scores such that the difference between the highest score and the lowest score in the selected group is as small as possible.
Return that minimum possible difference.
A group is any subset of k elements from the array. The selected scores do not need to be contiguous in the original order.
Key idea
The answer depends on how tightly k values can fit together after ordering the scores.
Input Format
scores: an array of integersk: an integer representing the number of scores to choose
Output Format
Return a single integer: the minimum possible difference between the maximum and minimum score among any selected group of size k.
Constraints
1 <= k <= scores.lengthscores.lengthis at least 1- Score values are integers
- Use a solution efficient enough for typical interview constraints
Example 1
Input
scores = [90, 100, 110, 120, 130], k = 3
Output
20
Explanation
After sorting, the best group is [90, 100, 110] or [100, 110, 120] or [110, 120, 130]. The smallest difference is 20.
Example 2
Input
scores = [9, 4, 1, 7], k = 2
Output
3
Explanation
Sort the scores to get [1, 4, 7, 9]. The best pair is [1, 4] or [4, 7] or [7, 9], each with difference 3.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.