Skip to content

Commit

Permalink
Add problem 1887: Reduction Operations to Make the Array Elements Equal
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 19, 2023
1 parent d542e0a commit 06b3521
Show file tree
Hide file tree
Showing 3 changed files with 60 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 @@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
pub struct Solution;

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

use std::cmp::Reverse;

impl Solution {
pub fn reduction_operations(nums: Vec<i32>) -> 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>) -> i32 {
Self::reduction_operations(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

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

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 06b3521

Please sign in to comment.