diff --git a/src/lib.rs b/src/lib.rs index 2a095848..b7efeba8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1758,6 +1758,7 @@ pub mod problem_2360_longest_cycle_in_a_graph; pub mod problem_2363_merge_similar_items; pub mod problem_2364_count_number_of_bad_pairs; pub mod problem_2365_task_scheduler_ii; +pub mod problem_2366_minimum_replacements_to_sort_the_array; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2366_minimum_replacements_to_sort_the_array/greedy.rs b/src/problem_2366_minimum_replacements_to_sort_the_array/greedy.rs new file mode 100644 index 00000000..1f68eacc --- /dev/null +++ b/src/problem_2366_minimum_replacements_to_sort_the_array/greedy.rs @@ -0,0 +1,46 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn minimum_replacement(nums: Vec) -> i64 { + let mut result = 0; + let mut right = u32::MAX; + + for &num in nums.iter().rev() { + let num = num as u32; + + if right < num { + let quotient = num / right; + let remainder = num % right; + + if remainder == 0 { + result += u64::from(quotient - 1); + } else { + result += u64::from(quotient); + right = num / (quotient + 1); + } + } else { + right = num; + } + } + + result as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn minimum_replacement(nums: Vec) -> i64 { + Self::minimum_replacement(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2366_minimum_replacements_to_sort_the_array/mod.rs b/src/problem_2366_minimum_replacements_to_sort_the_array/mod.rs new file mode 100644 index 00000000..40a41b7c --- /dev/null +++ b/src/problem_2366_minimum_replacements_to_sort_the_array/mod.rs @@ -0,0 +1,22 @@ +pub mod greedy; + +pub trait Solution { + fn minimum_replacement(nums: Vec) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[3, 9, 3] as &[_], 2), + (&[1, 2, 3, 4, 5], 0), + (&[12, 9, 7, 6, 17, 19, 21], 6), + ]; + + for (nums, expected) in test_cases { + assert_eq!(S::minimum_replacement(nums.to_vec()), expected); + } + } +}