diff --git a/src/lib.rs b/src/lib.rs index 73173fff..6bc74db8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1702,6 +1702,7 @@ pub mod problem_2285_maximum_total_importance_of_roads; pub mod problem_2287_rearrange_characters_to_make_target_string; pub mod problem_2288_apply_discount_to_prices; pub mod problem_2293_min_max_game; +pub mod problem_2294_partition_array_such_that_maximum_difference_is_k; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2294_partition_array_such_that_maximum_difference_is_k/iterative.rs b/src/problem_2294_partition_array_such_that_maximum_difference_is_k/iterative.rs new file mode 100644 index 00000000..9515aabe --- /dev/null +++ b/src/problem_2294_partition_array_such_that_maximum_difference_is_k/iterative.rs @@ -0,0 +1,40 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn partition_array(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + + nums.sort_unstable(); + + let mut result = 1; + let mut iter = nums.iter().copied(); + let mut last = iter.next().unwrap() + k; + + for num in iter { + if num > last { + result += 1; + last = num + k; + } + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn partition_array(nums: Vec, k: i32) -> i32 { + Self::partition_array(nums, k) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2294_partition_array_such_that_maximum_difference_is_k/mod.rs b/src/problem_2294_partition_array_such_that_maximum_difference_is_k/mod.rs new file mode 100644 index 00000000..d1506de6 --- /dev/null +++ b/src/problem_2294_partition_array_such_that_maximum_difference_is_k/mod.rs @@ -0,0 +1,22 @@ +pub mod iterative; + +pub trait Solution { + fn partition_array(nums: Vec, k: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ((&[3, 6, 1, 2, 5] as &[_], 2), 2), + ((&[1, 2, 3], 1), 2), + ((&[2, 2, 4, 5], 0), 3), + ]; + + for ((nums, k), expected) in test_cases { + assert_eq!(S::partition_array(nums.to_vec(), k), expected); + } + } +}