From 601943b15b97def4d8a93d50d593468fe9cd5a72 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 18 Jul 2024 22:05:13 +0800 Subject: [PATCH] Add problem 2139: Minimum Moves to Reach Target Score --- src/lib.rs | 1 + .../greedy.rs | 48 +++++++++++++++++++ .../mod.rs | 18 +++++++ 3 files changed, 67 insertions(+) create mode 100644 src/problem_2139_minimum_moves_to_reach_target_score/greedy.rs create mode 100644 src/problem_2139_minimum_moves_to_reach_target_score/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 311a4d19..85b45724 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1545,6 +1545,7 @@ pub mod problem_2133_check_if_every_row_and_column_contains_all_numbers; pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii; pub mod problem_2135_count_words_obtained_after_adding_a_letter; pub mod problem_2138_divide_a_string_into_groups_of_size_k; +pub mod problem_2139_minimum_moves_to_reach_target_score; pub mod problem_2140_solving_questions_with_brainpower; pub mod problem_2144_minimum_cost_of_buying_candies_with_discount; pub mod problem_2145_count_the_hidden_sequences; diff --git a/src/problem_2139_minimum_moves_to_reach_target_score/greedy.rs b/src/problem_2139_minimum_moves_to_reach_target_score/greedy.rs new file mode 100644 index 00000000..b4df78ed --- /dev/null +++ b/src/problem_2139_minimum_moves_to_reach_target_score/greedy.rs @@ -0,0 +1,48 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn min_moves(target: i32, max_doubles: i32) -> i32 { + let mut target = target as u32; + let mut max_doubles = max_doubles as u32; + let mut result = 0; + + if target > 1 { + loop { + if max_doubles == 0 { + result += target - 1; + + break; + } + + result += (target & 1) + 1; + target >>= 1; + + if target > 1 { + max_doubles -= 1; + } else { + break; + } + } + } + + result as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn min_moves(target: i32, max_doubles: i32) -> i32 { + Self::min_moves(target, max_doubles) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2139_minimum_moves_to_reach_target_score/mod.rs b/src/problem_2139_minimum_moves_to_reach_target_score/mod.rs new file mode 100644 index 00000000..0f252896 --- /dev/null +++ b/src/problem_2139_minimum_moves_to_reach_target_score/mod.rs @@ -0,0 +1,18 @@ +pub mod greedy; + +pub trait Solution { + fn min_moves(target: i32, max_doubles: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [((5, 0), 4), ((19, 2), 7), ((10, 4), 4), ((1, 100), 0)]; + + for ((target, max_doubles), expected) in test_cases { + assert_eq!(S::min_moves(target, max_doubles), expected); + } + } +}