1984. Minimum Difference Between Highest And Lowest of K Scores - Explanation

Problem Link

Description

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: 1

Explanation: 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: 2

Explanation: We can pick [9,7], whose score is 2 which is minimum among all combinations.

Constraints:

  • 1 <= k <= nums.length <= 1000
  • 0 <= nums[i] <= 100,000

Company Tags

Please upgrade to NeetCode Pro to view company tags.



1. Sorting + Sliding Window

class Solution:
    def minimumDifference(self, nums: List[int], k: int) -> int:
        nums.sort()
        l, r = 0, k - 1
        res = float("inf")
        while r < len(nums):
            res = min(res, nums[r] - nums[l])
            l += 1
            r += 1
        return res

Time & Space Complexity

  • Time complexity: O(nlogn)O(n \log n)
  • Space complexity: O(1)O(1) or O(n)O(n) depending on the sorting algorithm.