From aa6e1a58e99ba6f4a3598d81796748f4cabba90a Mon Sep 17 00:00:00 2001 From: Rodolfo P A <6721075+rodoufu@users.noreply.github.com> Date: Mon, 29 May 2023 12:23:14 -0300 Subject: [PATCH] Create minimum-difference-between-highest-and-lowest-of-k-scores.rs --- ...-between-highest-and-lowest-of-k-scores.rs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 leetCode/array/minimum-difference-between-highest-and-lowest-of-k-scores.rs diff --git a/leetCode/array/minimum-difference-between-highest-and-lowest-of-k-scores.rs b/leetCode/array/minimum-difference-between-highest-and-lowest-of-k-scores.rs new file mode 100644 index 0000000..25c6fce --- /dev/null +++ b/leetCode/array/minimum-difference-between-highest-and-lowest-of-k-scores.rs @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores +impl Solution { + pub fn minimum_difference(nums: Vec, k: i32) -> i32 { + if nums.len() == 1 { + return 0; + } + + let mut nums = nums; + nums.sort(); + + // println!("nums:{nums:?}"); + + let mut cur = 0; + for i in 1..(k as usize) { + cur += nums[i] - nums[i - 1]; + // println!("cur:{cur}, i:{i}, nums[i]:{}, nums[i - 1]:{}", nums[i], nums[i - 1]); + } + + let mut resp = cur; + // println!("resp:{resp}, cur:{cur}"); + for i in (k as usize)..nums.len() { + cur = cur - nums[i - k as usize + 1] + nums[i - k as usize] + nums[i] - nums[i - 1]; + // println!( + // "cur:{cur}, i:{i}, nums[i - k as usize + 1]:{}, nums[i - k as usize]:{}, nums[i]:{}, nums[i - 1]:{}", + // nums[i - k as usize + 1], nums[i - k as usize], nums[i], nums[i - 1], + // ); + if cur < resp { + resp = cur; + } + // println!("resp:{resp}, cur:{cur}"); + } + + resp + } +}