Problem Description
Given an array of scores and an integer k, select any k scores such that the difference between the highest and the lowest score in the selection is minimized. Return this minimum possible difference.
Key Insights
- Sorting the array simplifies the problem since the minimum difference among k scores will be found in a contiguous subarray.
- A sliding window approach of size k on the sorted array allows us to efficiently evaluate each candidate set.
- Compute the difference between the first and last elements in each window, and track the minimum difference found.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(1) if sorting is done in-place, otherwise O(n) for the sorted copy.
Solution
Sort the input array first to line up scores in non-decreasing order. Then, use a sliding window of size k to evaluate every contiguous block of k elements in the sorted array. In each block, the difference between the maximum (last element) and minimum (first element) is computed. The minimum of these differences over all possible windows is the answer. This approach efficiently leverages the sorted order to simplify the evaluation of potential candidate sets.