Skip to content

Commit

Permalink
Add problem 2366: Minimum Replacements to Sort the Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 20, 2024
1 parent c86a11e commit 0b7f4c3
Show file tree
Hide file tree
Showing 3 changed files with 69 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 @@ -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;
46 changes: 46 additions & 0 deletions src/problem_2366_minimum_replacements_to_sort_the_array/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn minimum_replacement(nums: Vec<i32>) -> 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<i32>) -> i64 {
Self::minimum_replacement(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
22 changes: 22 additions & 0 deletions src/problem_2366_minimum_replacements_to_sort_the_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod greedy;

pub trait Solution {
fn minimum_replacement(nums: Vec<i32>) -> i64;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 0b7f4c3

Please sign in to comment.