You are given a list of scores of different students, scores, where scores[i] represents the score of the i-th student. You are also given an integer k, which represents the number of students to consider. Your task is to pick k scores from the list scores such that the difference between the highest and lowest scores in this subset is minimized. Return the minimum difference.
Example:
scores = [90, 100, 78, 89, 67, 85], k = 3k is always a valid integer (1 ≤ k ≤ len(scores))?
k is always valid.scores be?
scores can be up to 10^5.The strategy to solve this problem involves sorting the list of scores and then using a sliding window of size k to find the minimum difference between the highest and lowest scores within any subset of k consecutive scores.
k over the sorted list:
This approach ensures that we efficiently find the minimum possible difference.
from typing import List
def minimumDifference(scores: List[int], k: int) -> int:
# Step 1: Sort the scores
scores.sort()
# Step 2: Initialize the minimum difference with a large value
min_diff = float('inf')
# Step 3: Slide a window of size k
for i in range(len(scores) - k + 1):
# Compute the difference between the current window's highest and lowest scores
current_diff = scores[i + k - 1] - scores[i]
# Update the minimum difference
min_diff = min(min_diff, current_diff)
return min_diff
# Example usage:
scores = [90, 100, 78, 89, 67, 85]
k = 3
print(minimumDifference(scores, k)) # Output: 5
scores.This solution is efficient and should work within the problem constraints.
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?