Skip to content

Commit

Permalink
Add problem 1984: Minimum Difference Between Highest and Lowest of K …
Browse files Browse the repository at this point in the history
…Scores
  • Loading branch information
EFanZh committed Dec 4, 2023
1 parent 3690c3a commit 2642a2e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,7 @@ pub mod problem_1974_minimum_time_to_type_word_using_special_typewriter;
pub mod problem_1975_maximum_matrix_sum;
pub mod problem_1979_find_greatest_common_divisor_of_array;
pub mod problem_1980_find_unique_binary_string;
pub mod problem_1984_minimum_difference_between_highest_and_lowest_of_k_scores;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod sliding_window;

pub trait Solution {
fn minimum_difference(nums: Vec<i32>, k: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((&[90] as &[_], 1), 0), ((&[9, 4, 1, 7], 2), 2)];

for ((nums, k), expected) in test_cases {
assert_eq!(S::minimum_difference(nums.to_vec(), k), expected);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
let mut nums = nums;

nums.sort_unstable();

nums.iter()
.zip(&nums[k as u32 as usize - 1..])
.fold(i32::MAX, |result, (left, right)| result.min(right - left))
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
Self::minimum_difference(nums, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 2642a2e

Please sign in to comment.