Teaching Kids Programming: Videos on Data Structures and Algorithms
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 = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:
– [90]. The difference between the highest and lowest score is 90 – 90 = 0.
The minimum possible difference is 0.Example 2:
Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:
– [9,4,1,7]. The difference between the highest and lowest score is 9 – 4 = 5.
– [9,4,1,7]. The difference between the highest and lowest score is 9 – 1 = 8.
– [9,4,1,7]. The difference between the highest and lowest score is 9 – 7 = 2.
– [9,4,1,7]. The difference between the highest and lowest score is 4 – 1 = 3.
– [9,4,1,7]. The difference between the highest and lowest score is 7 – 4 = 3.
– [9,4,1,7]. The difference between the highest and lowest score is 7 – 1 = 6.
The minimum possible difference is 2.Constraints:
1 <= k <= nums.length <= 1000
0 <= nums[i] <= 10^5Hints:
For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible.
What if the array was sorted?
After sorting the scores, any contiguous k scores are as close to each other as possible.
Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.
Minimum Difference Between Highest and Lowest of K Scores via Sorting
We can bruteforce, for sure. Picking K numbers out of N numbers has time complexity O(C(N, K)) and for each K-size subarray, we need O(K) time to find the max/min – which means the overall time complexity is O(K*(C(N, K))).
However, we can sort the original array, can iterate over the K-size subarray. This works because we want the min and max of sub array to be as small as possible, by sorting, we get the optimal sub array.
1 2 3 4 5 | class Solution: def minimumDifference(self, nums: List[int], k: int) -> int: nums.sort() # return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1)) return min(nums[i] - nums[i - k + 1] for i in range(k - 1, len(nums))) |
class Solution: def minimumDifference(self, nums: List[int], k: int) -> int: nums.sort() # return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1)) return min(nums[i] - nums[i - k + 1] for i in range(k - 1, len(nums)))
The overall time complexity is O(NLogN) due to sorting the array.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Work Everywhere: Build a Serverless Visual Studio Code in Browser using Railway
Next Post: Teaching Kids Programming - Evaluate Reverse Polish Notation