Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created January 25, 2026 18:31
Show Gist options
  • Select an option

  • Save tatsuyax25/fc57a42d5cfc10564118f094d71df7b6 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/fc57a42d5cfc10564118f094d71df7b6 to your computer and use it in GitHub Desktop.
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
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minimumDifference = function(nums, k) {
// If k is 1, picking a single student always gives difference = 0
if (k === 1) return 0;
// Sort scores so close values sit next to each other
nums.sort((a, b) => a - b);
// We'll track the smallest range found
let minDiff = Infinity;
// Slide a window of size k across the sorted array
// Window goes from index i to i + k - 1
for (let i = 0; i + k - 1 < nums.length; i++) {
const currentDiff = nums[i + k - 1] - nums[i];
minDiff = Math.min(minDiff, currentDiff);
}
return minDiff;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment