Skip to content

Commit

Permalink
Add problem 2009: Minimum Number of Operations to Make Array Continuous
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Aug 12, 2024
1 parent 5868db3 commit 6041112
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 @@ -1486,6 +1486,7 @@ pub mod problem_2003_smallest_missing_genetic_value_in_each_subtree;
pub mod problem_2006_count_number_of_pairs_with_absolute_difference_k;
pub mod problem_2007_find_original_array_from_doubled_array;
pub mod problem_2008_maximum_earnings_from_taxi;
pub mod problem_2009_minimum_number_of_operations_to_make_array_continuous;
pub mod problem_2011_final_value_of_variable_after_performing_operations;
pub mod problem_2012_sum_of_beauty_in_the_array;
pub mod problem_2013_detect_squares;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
pub struct Solution;

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

impl Solution {
pub fn min_operations(nums: Vec<i32>) -> i32 {
let mut nums = nums;
let n = nums.len() as u32;

nums.sort_unstable();
nums.dedup();

let mut start = 0;

for &num in &nums {
if nums[start] <= num - n as i32 {
start += 1;
}
}

let n2 = nums.len() as u32;

drop(nums);

(n - (n2 - start as u32)) as _
}
}

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

impl super::Solution for Solution {
fn min_operations(nums: Vec<i32>) -> i32 {
Self::min_operations(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod iterative;

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

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

pub fn run<S: Solution>() {
let test_cases = [
(&[4, 2, 5, 3] as &[_], 0),
(&[1, 2, 3, 5, 6], 1),
(&[1, 10, 100, 1000], 3),
(&[8, 5, 9, 9, 8, 4], 2),
];

for (nums, expected) in test_cases {
assert_eq!(S::min_operations(nums.to_vec()), expected);
}
}
}

0 comments on commit 6041112

Please sign in to comment.