From 06b3521237ad9a4d1d20d1552e416c0da61e1be9 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 19 Oct 2023 22:23:48 +0800 Subject: [PATCH] Add problem 1887: Reduction Operations to Make the Array Elements Equal --- src/lib.rs | 1 + .../iterative.rs | 41 +++++++++++++++++++ .../mod.rs | 18 ++++++++ 3 files changed, 60 insertions(+) create mode 100644 src/problem_1887_reduction_operations_to_make_the_array_elements_equal/iterative.rs create mode 100644 src/problem_1887_reduction_operations_to_make_the_array_elements_equal/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 72543076..6e4fde95 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1451,6 +1451,7 @@ pub mod problem_1880_check_if_word_equals_summation_of_two_words; pub mod problem_1881_maximum_value_after_insertion; pub mod problem_1884_egg_drop_with_2_eggs_and_n_floors; pub mod problem_1886_determine_whether_matrix_can_be_obtained_by_rotation; +pub mod problem_1887_reduction_operations_to_make_the_array_elements_equal; #[cfg(test)] mod test_utilities; diff --git a/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/iterative.rs b/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/iterative.rs new file mode 100644 index 00000000..9a39176c --- /dev/null +++ b/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/iterative.rs @@ -0,0 +1,41 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::cmp::Reverse; + +impl Solution { + pub fn reduction_operations(nums: Vec) -> i32 { + let mut nums = nums; + + nums.sort_unstable_by_key(|&num| Reverse(num as u32)); + + let mut result = 0; + let mut prev = 0; + + for (count, num) in (0..).zip(nums) { + if num != prev { + result += count; + prev = num; + } + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn reduction_operations(nums: Vec) -> i32 { + Self::reduction_operations(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/mod.rs b/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/mod.rs new file mode 100644 index 00000000..8d51a932 --- /dev/null +++ b/src/problem_1887_reduction_operations_to_make_the_array_elements_equal/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn reduction_operations(nums: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[5, 1, 3] as &[_], 3), (&[1, 1, 1], 0), (&[1, 1, 2, 2, 3], 4)]; + + for (nums, expected) in test_cases { + assert_eq!(S::reduction_operations(nums.to_vec()), expected); + } + } +}