LeetCode Entry
1984. Minimum Difference Between Highest and Lowest of K Scores
Min k-diff window
1984. Minimum Difference Between Highest and Lowest of K Scores easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1248
Problem TLDR
Min k-diff #easy #sliding_window
Intuition
Sort, then do a sliding window.
Approach
- use windows(k) or zip(skip(k))
Complexity
-
Time complexity: \(O(nlog(n))\)
-
Space complexity: \(O(n)\) or O(1)
Code
// 18ms
fun minimumDifference(n: IntArray, k: Int) =
n.run{sort();(k..size).minOfOrNull{n[it-1]-n[it-k]}?:0}
// 1ms
pub fn minimum_difference(mut n: Vec<i32>, k: i32) -> i32 {
n.sort(); n.iter().zip(n.iter().skip(k as usize-1)).map(|(a,b)|b-a).min().unwrap_or(0)
}