Leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores
You are given a list of integers nums
representing the scores of students in a class and an integer k
. Your goal is to find the minimum possible difference between the highest and lowest scores among any k
students.
nums
and k
?k
be larger than the length of nums
?nums
have (positive, negative, or zero)?nums
guaranteed to be unique?For this problem, let’s assume:
2 <= k <= nums.size() <= 1000
.nums
contains positive integers.nums
are not necessarily unique.The main strategy here is to sort the array and then use a sliding window of size k
to find the minimum difference between the maximum and minimum elements in the window.
k
to traverse the sorted array and keep track of the minimum difference between the highest and lowest scores in the window.#include <vector>
#include <algorithm>
#include <iostream>
class Solution {
public:
int minimumDifference(std::vector<int>& nums, int k) {
// Sort the array
std::sort(nums.begin(), nums.end());
// Initialize the minimum difference to a large value
int min_diff = INT_MAX;
// Iterate through the sorted list using a sliding window of size k
for (int i = 0; i <= nums.size() - k; ++i) {
int current_diff = nums[i + k - 1] - nums[i];
min_diff = std::min(min_diff, current_diff);
}
return min_diff;
}
};
// Example usage:
int main() {
Solution sol;
std::vector<int> nums = {90, 100, 78, 89, 67, 56, 89, 120};
int k = 3;
std::cout << sol.minimumDifference(nums, k) << std::endl; // Output should be the minimum difference
return 0;
}
k
consecutive elements.k
can still fit. Calculate the difference between the maximum and minimum in the current window and update the minimum difference found so far.nums
.This approach efficiently finds the minimum possible difference between the highest and lowest scores among any k
students.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?