Minimum Difference Between Highest and Lowest of K Scores

easy array sorting sliding window

Problem

You are given an array nums of positive integers and an integer k. Pick any k scores from the array; let the chosen scores have minimum value lo and maximum value hi. Return the minimum possible value of hi − lo.

Inputnums = [9, 4, 1, 7], k = 2
Output2
After sorting [1,4,7,9], adjacent pair (7,9) gives the smallest diff = 2.

def minimum_difference(nums, k):
    nums.sort()
    best = float('inf')
    for i in range(len(nums) - k + 1):
        best = min(best, nums[i + k - 1] - nums[i])
    return best
function minimumDifference(nums, k) {
  nums.sort((a, b) => a - b);
  let best = Infinity;
  for (let i = 0; i + k - 1 < nums.length; i++) {
    best = Math.min(best, nums[i + k - 1] - nums[i]);
  }
  return best;
}
class Solution {
    public int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int best = Integer.MAX_VALUE;
        for (int i = 0; i + k - 1 < nums.length; i++) {
            best = Math.min(best, nums[i + k - 1] - nums[i]);
        }
        return best;
    }
}
int minimumDifference(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int best = INT_MAX;
    for (int i = 0; i + k - 1 < (int)nums.size(); i++) {
        best = min(best, nums[i + k - 1] - nums[i]);
    }
    return best;
}
Time: O(n log n) Space: O(1)