From 16d670ea80cb65785fa6a16781260cd130ac6483 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Fri, 17 Nov 2023 23:42:32 +0800 Subject: [PATCH] Add problem 1962: Remove Stones to Minimize the Total --- src/lib.rs | 1 + .../binary_heap.rs | 35 +++++++++++++++++++ .../mod.rs | 18 ++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/problem_1962_remove_stones_to_minimize_the_total/binary_heap.rs create mode 100644 src/problem_1962_remove_stones_to_minimize_the_total/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 5d2733e0..37e3b217 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1480,6 +1480,7 @@ pub mod problem_1945_sum_of_digits_of_string_after_convert; pub mod problem_1952_three_divisors; pub mod problem_1957_delete_characters_to_make_fancy_string; pub mod problem_1961_check_if_string_is_a_prefix_of_array; +pub mod problem_1962_remove_stones_to_minimize_the_total; #[cfg(test)] mod test_utilities; diff --git a/src/problem_1962_remove_stones_to_minimize_the_total/binary_heap.rs b/src/problem_1962_remove_stones_to_minimize_the_total/binary_heap.rs new file mode 100644 index 00000000..0987e176 --- /dev/null +++ b/src/problem_1962_remove_stones_to_minimize_the_total/binary_heap.rs @@ -0,0 +1,35 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::collections::BinaryHeap; + +impl Solution { + pub fn min_stone_sum(piles: Vec, k: i32) -> i32 { + let mut queue = BinaryHeap::from(piles); + + for _ in 0..k { + let num = &mut *queue.peek_mut().unwrap(); + + *num = (*num + 1) / 2; + } + + queue.iter().sum() + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn min_stone_sum(piles: Vec, k: i32) -> i32 { + Self::min_stone_sum(piles, k) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1962_remove_stones_to_minimize_the_total/mod.rs b/src/problem_1962_remove_stones_to_minimize_the_total/mod.rs new file mode 100644 index 00000000..5a50629e --- /dev/null +++ b/src/problem_1962_remove_stones_to_minimize_the_total/mod.rs @@ -0,0 +1,18 @@ +pub mod binary_heap; + +pub trait Solution { + fn min_stone_sum(piles: Vec, k: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [((&[5, 4, 9] as &[_], 2), 12), ((&[4, 3, 6, 7], 3), 12)]; + + for ((piles, k), expected) in test_cases { + assert_eq!(S::min_stone_sum(piles.to_vec(), k), expected); + } + } +}