LeetCode-in-Java

1984. Minimum Difference Between Highest and Lowest of K Scores

Easy

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:

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:

The minimum possible difference is 2.

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    public int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int minDiff = nums[nums.length - 1];
        for (int i = 0; i <= nums.length - k; i++) {
            minDiff = Math.min(minDiff, nums[i + k - 1] - nums[i]);
        }
        return minDiff;
    }
}