1984. Minimum Difference Between Highest and Lowest of K Scores Easy
1/**
2 * [1984] Minimum Difference Between Highest and Lowest of K Scores
3 *
4 * You are given a 0-indexed integer array nums, where nums[i] represents the score of the i^th student. You are also given an integer k.
5 * 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.
6 * Return the minimum possible difference.
7 *
8 * Example 1:
9 *
10 * Input: nums = [90], k = 1
11 * Output: 0
12 * Explanation: There is one way to pick score(s) of one student:
13 * - [<u>90</u>]. The difference between the highest and lowest score is 90 - 90 = 0.
14 * The minimum possible difference is 0.
15 *
16 * Example 2:
17 *
18 * Input: nums = [9,4,1,7], k = 2
19 * Output: 2
20 * Explanation: There are six ways to pick score(s) of two students:
21 * - [<u>9</u>,<u>4</u>,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
22 * - [<u>9</u>,4,<u>1</u>,7]. The difference between the highest and lowest score is 9 - 1 = 8.
23 * - [<u>9</u>,4,1,<u>7</u>]. The difference between the highest and lowest score is 9 - 7 = 2.
24 * - [9,<u>4</u>,<u>1</u>,7]. The difference between the highest and lowest score is 4 - 1 = 3.
25 * - [9,<u>4</u>,1,<u>7</u>]. The difference between the highest and lowest score is 7 - 4 = 3.
26 * - [9,4,<u>1</u>,<u>7</u>]. The difference between the highest and lowest score is 7 - 1 = 6.
27 * The minimum possible difference is 2.
28 *
29 * Constraints:
30 *
31 * 1 <= k <= nums.length <= 1000
32 * 0 <= nums[i] <= 10^5
33 *
34 */
35pub struct Solution {}
36
37// problem: https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/
38// discuss: https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/discuss/?currentPage=1&orderBy=most_votes&query=
39
40// submission codes start here
41
42impl Solution {
43 pub fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
44 let mut n = nums.clone();
45 n.sort();
46 let mut result = i32::MAX;
47
48 for i in 0..n.len() - k as usize + 1 {
49 if n[i + k as usize - 1] - n[i] < result {
50 result = n[i + k as usize - 1] - n[i];
51 }
52 }
53 result
54 }
55}
56
57// submission codes end
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_1984() {
65 assert_eq!(Solution::minimum_difference(vec![9,4,1,7], 2), 2);
66 }
67}
68
Back
© 2025 bowen.ge All Rights Reserved.