Leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores
You are given a list of integers scores representing the scores of a game and an integer k. Your task is to find the minimum difference between the highest and lowest scores in any k-subarray of scores. A k-subarray is a subarray of length k.
Constraints:
1 <= k <= scores.length <= 10000 <= scores[i] <= 10^5To solve this problem, you’ll use the following steps:
k.Here is the Java implementation for the problem:
import java.util.Arrays;
public class MinimumDifferenceBetweenScores {
public int minimumDifference(int[] scores, int k) {
// If k is 1, the minimum difference is always 0
if (k == 1) return 0;
// Step 1: Sort the array
Arrays.sort(scores);
int minDifference = Integer.MAX_VALUE;
// Step 2: Use sliding window approach
for (int i = 0; i <= scores.length - k; i++) {
int currentDifference = scores[i + k - 1] - scores[i];
if (currentDifference < minDifference) {
minDifference = currentDifference;
}
}
return minDifference;
}
public static void main(String[] args) {
MinimumDifferenceBetweenScores solution = new MinimumDifferenceBetweenScores();
int[] scores = {9, 4, 1, 7};
int k = 2;
System.out.println(solution.minimumDifference(scores, k)); // Output: 2
}
}
O(n log n), where n is the length of the array.O(n), as we slide the window across the array.Hence, the overall time complexity is dominated by the sorting step, resulting in O(n log n).
This should cover the problem comprehensively and provide a clear and efficient solution using Java.
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?