Skip to content

Commit

Permalink
Add problem 2171: Removing Minimum Number of Magic Beans
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jul 11, 2024
1 parent 3852874 commit 582a6dc
Show file tree
Hide file tree
Showing 3 changed files with 62 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 @@ -1559,6 +1559,7 @@ pub mod problem_2165_smallest_value_of_the_rearranged_number;
pub mod problem_2166_design_bitset;
pub mod problem_2169_count_operations_to_obtain_zero;
pub mod problem_2170_minimum_operations_to_make_the_array_alternating;
pub mod problem_2171_removing_minimum_number_of_magic_beans;
pub mod problem_2177_find_three_consecutive_integers_that_sum_to_a_given_number;
pub mod problem_2180_count_integers_with_even_digit_sum;
pub mod problem_2181_merge_nodes_in_between_zeros;
Expand Down
18 changes: 18 additions & 0 deletions src/problem_2171_removing_minimum_number_of_magic_beans/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod sorting;

pub trait Solution {
fn minimum_removal(beans: Vec<i32>) -> i64;
}

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

pub fn run<S: Solution>() {
let test_cases = [(&[4, 1, 6, 5] as &[_], 4), (&[2, 10, 3, 2], 7)];

for (beans, expected) in test_cases {
assert_eq!(S::minimum_removal(beans.to_vec()), expected);
}
}
}
43 changes: 43 additions & 0 deletions src/problem_2171_removing_minimum_number_of_magic_beans/sorting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
pub struct Solution;

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

impl Solution {
pub fn minimum_removal(beans: Vec<i32>) -> i64 {
let mut beans = beans.into_iter().map(|x| x as u32).collect::<Vec<_>>();

beans.sort_unstable();

let mut left_sum = 0;
let mut right_length = beans.len() as u64;
let mut right_sum = beans.iter().fold(0_u64, |sum, &x| sum + u64::from(x));

beans.into_iter().fold(u64::MAX, |mut result, value| {
let value = u64::from(value);

result = result.min(left_sum + (right_sum - value * right_length));

left_sum += value;
right_length -= 1;
right_sum -= value;

result
}) as _
}
}

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

impl super::Solution for Solution {
fn minimum_removal(beans: Vec<i32>) -> i64 {
Self::minimum_removal(beans)
}
}

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

0 comments on commit 582a6dc

Please sign in to comment.