Post

2112 Minimum Difference Between Highest And Lowest Of K Scores

2112 Minimum Difference Between Highest And Lowest Of K Scores

Minimum Difference Between Highest and Lowest of K Scores image

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:

1
2
3
4
5
6
7
**Input:** nums = [90], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- [**90**]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.

Example 2:

1
2
3
4
5
6
7
8
9
10
11
**Input:** nums = [9,4,1,7], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- [**9**,**4**,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [**9**,4,**1**,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [**9**,4,1,**7**]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,**4**,**1**,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,**4**,1,**7**]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,**1**,**7**]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.

 

Constraints:

1
2
1 <= k <= nums.length <= 1000
0 <= nums[i] <= 105
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

impl Solution {
    pub fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
        if k <= 1 || k as usize > nums.len() {
            return 0;
        }

        let mut arr = nums.clone();
        arr.sort();

        let k = k as usize;
        let mut m = k - 1;
        let mut diff = i32::MAX;

        while m < arr.len() {
            diff = diff.min(arr[m] - arr[m - k + 1]);
            m += 1;
        }

        diff
    }
}




This post is licensed under CC BY 4.0 by the author.