Approach
When select k score that have a minimum difference, we would like to make them as close as possible.
Therefore, we sort the array and chekc all continuous k elements max difference (that is the i and i+k-1 element’s difference after sorting), ans find the minimum among them.
Code
class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
int minVal = nums[n-1] - nums[0];
for(int i = 0 ; i <= n-k ; ++i) {
minVal = min(minVal, nums[i+k-1] - nums[i]);
}
return minVal;
}
};