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 = [2,5,3,1,6,3], k = 3
Output: 1Explanation: We can pick [2,3,3], whose score is 1 which is minimum among all combinations.
Example 2:
Input: nums = [9,4,1,7], k = 2
Output: 2Explanation: We can pick [9,7], whose score is 2 which is minimum among all combinations.
Constraints:
1 <= k <= nums.length <= 10000 <= nums[i] <= 100,000Before attempting this problem, you should be comfortable with:
When we need to minimize the difference between the highest and lowest values among any k chosen elements, sorting the array first is key. After sorting, the smallest possible range of k elements will always be a contiguous segment. Why? Because picking non-adjacent elements after sorting would only increase the gap between max and min. So, we sort the array and then slide a window of size k across it, tracking the minimum difference between the first and last element of each window.
l = 0 and r = k - 1 to represent a window of size k.res to infinity to track the minimum difference found.r is within bounds:nums[r] - nums[l] (the difference between max and min in this window).res with the minimum of the current res and this difference.l and r.res.The sliding window approach only works on a sorted array because it relies on contiguous elements having the minimum possible range. Applying the window on an unsorted array compares arbitrary elements, missing the optimal k-element subset.
The window should contain exactly k elements, meaning if l is the left index and r is the right index, then r - l + 1 = k, so r = l + k - 1. Initializing r = k instead of r = k - 1 creates a window of size k + 1, producing incorrect difference calculations.