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 <= 10000 <= nums[i] <= 105
Solutions
This solution is functionally identical to the previous one but uses a different coding style: it pre-calculates the array length in n, replaces Math.min() with an explicit if statement, and renames diff to min. After sorting the array, it applies a sliding window of size k to find the minimum difference between elements k positions apart, returning the smallest difference found across all windows.
Language: javascript(2026-01-25 10:23)DONE
CPU Performance80.82%
Memory Performance27.40%
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minimumDifference = function(nums, k) {
nums.sort((a, b) => a - b);
const n = nums.length;
let min = Infinity;
for (let i = k - 1; i < n; i++) {
const diff = nums[i] - nums[i - k + 1];
if (diff < min) {
min = diff;
}
}
return min === Infinity ? 0 : min;
};