diff --git a/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.lock b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.lock new file mode 100644 index 0000000..a02f203 --- /dev/null +++ b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "minimum_number_of_operations_to_move_all_balls_to_each_box" +version = "0.1.0" diff --git a/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.toml b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.toml new file mode 100644 index 0000000..edbba45 --- /dev/null +++ b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "minimum_number_of_operations_to_move_all_balls_to_each_box" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/src/lib.rs b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/src/lib.rs new file mode 100644 index 0000000..55485e9 --- /dev/null +++ b/1769_minimum_number_of_operations_to_move_all_balls_to_each_box/src/lib.rs @@ -0,0 +1,33 @@ +pub struct Solution; + +impl Solution { + pub fn min_operations(boxes: String) -> Vec { + let boxes: Vec = boxes.chars().map(|c| c as i32 - 48).collect(); + + let mut balls_counted_from_left = vec![0; boxes.len()]; + for i in 1..boxes.len() { + balls_counted_from_left[i] = balls_counted_from_left[i - 1] + boxes[i - 1]; + } + + let mut balls_counted_from_right = vec![0; boxes.len()]; + for i in (0..(boxes.len() - 1)).rev() { + balls_counted_from_right[i] = balls_counted_from_right[i + 1] + boxes[i + 1]; + } + + let mut steps_moving_to_right = vec![0; boxes.len()]; + for i in 1..boxes.len() { + steps_moving_to_right[i] = steps_moving_to_right[i - 1] + balls_counted_from_left[i]; + } + + let mut steps_moving_to_left = vec![0; boxes.len()]; + for i in (0..(boxes.len() - 1)).rev() { + steps_moving_to_left[i] = steps_moving_to_left[i + 1] + balls_counted_from_right[i]; + } + + steps_moving_to_left + .iter() + .zip(steps_moving_to_right.iter()) + .map(|(&l, &r)| l + r) + .collect() + } +}