Skip to content

1984. Minimum Difference Between Highest and Lowest of K Scores

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int minimumDifference(vector<int>& nums, int k) {
    ranges::sort(nums);

    int ans = nums[k - 1] - nums[0];

    for (int i = k; i < nums.size(); ++i)
      ans = min(ans, nums[i] - nums[i - k + 1]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int minimumDifference(int[] nums, int k) {
    Arrays.sort(nums);

    int ans = nums[k - 1] - nums[0];

    for (int i = k; i < nums.length; ++i)
      ans = Math.min(ans, nums[i] - nums[i - k + 1]);

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def minimumDifference(self, nums: list[int], k: int) -> int:
    nums.sort()
    ans = nums[k - 1] - nums[0]

    for i in range(k, len(nums)):
      ans = min(ans, nums[i] - nums[i - k + 1])

    return ans