Leetcode 1984: Minimum Difference Between Highest and Lowest of K Scores

grid47
grid47
Exploring patterns and algorithms
Apr 22, 2024 4 min read

You are given a 0-indexed array nums where each element represents the score of a student. You need to select the scores of exactly k students such that the difference between the highest and the lowest score of the selected students is minimized. Your task is to return the minimum possible difference.
Problem
Approach
Steps
Complexity
Input: You are provided with an integer array nums and an integer k.
Example: nums = [1, 3, 8, 7, 9], k = 3
Constraints:
• 1 <= k <= nums.length <= 1000
• 0 <= nums[i] <= 10^5
Output: Return the minimum possible difference between the highest and the lowest score of the selected k students.
Example: Output: 2
Constraints:
• The returned value must be the smallest possible difference.
Goal: The goal is to select a subset of k students from the array such that the difference between the highest and the lowest score in that subset is minimized.
Steps:
• Sort the array to make the differences easier to calculate.
• Iterate through the sorted array and consider every contiguous subsequence of length k.
• For each subsequence, calculate the difference between the first and the last element, then track the minimum difference.
Goal: The input array can be large, so the algorithm should be efficient.
Steps:
• The solution should handle arrays of up to 1000 elements efficiently.
Assumptions:
• The array is not empty, and k is at least 1.
Input: Input: nums = [1, 3, 8, 7, 9], k = 3
Explanation: After sorting the array, we get [1, 3, 7, 8, 9]. Selecting the students with scores 3, 7, and 8 gives a difference of 8 - 3 = 5. The minimum possible difference is 2.

Input: Input: nums = [5, 2, 9, 4], k = 2
Explanation: The sorted array is [2, 4, 5, 9]. Choosing the students with scores 4 and 5 results in a difference of 5 - 4 = 1. This is the minimum possible difference.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus