Skip to content

Commit

Permalink
Add problem 2139: Minimum Moves to Reach Target Score
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jul 18, 2024
1 parent 620f51f commit 601943b
Show file tree
Hide file tree
Showing 3 changed files with 67 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 @@ -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;
Expand Down
48 changes: 48 additions & 0 deletions src/problem_2139_minimum_moves_to_reach_target_score/greedy.rs
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2139_minimum_moves_to_reach_target_score/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 601943b

Please sign in to comment.