diff --git a/src/lib.rs b/src/lib.rs index e944617b..deb29adb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1442,6 +1442,7 @@ pub mod problem_2119_a_number_after_a_double_reversal; pub mod problem_2124_check_if_all_as_appears_before_all_bs; pub mod problem_2129_capitalize_the_title; pub mod problem_2130_maximum_twin_sum_of_a_linked_list; +pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/mod.rs b/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/mod.rs new file mode 100644 index 00000000..0f7497e0 --- /dev/null +++ b/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/mod.rs @@ -0,0 +1,22 @@ +pub mod sliding_window; + +pub trait Solution { + fn min_swaps(nums: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[0, 1, 0, 1, 1, 0, 0] as &[_], 1), + (&[0, 1, 1, 1, 0, 0, 1, 1, 0], 2), + (&[1, 1, 0, 0, 1], 0), + ]; + + for (nums, expected) in test_cases { + assert_eq!(S::min_swaps(nums.to_vec()), expected); + } + } +} diff --git a/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/sliding_window.rs b/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/sliding_window.rs new file mode 100644 index 00000000..57638d7a --- /dev/null +++ b/src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/sliding_window.rs @@ -0,0 +1,48 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn min_swaps(nums: Vec) -> i32 { + let n = nums.len() as u32; + let ones = nums.iter().sum::() as u32; + + let (left, right) = nums.split_at(ones as usize); + let mut window_ones = left.iter().sum::() as u32; + let mut max_windows_ones = window_ones; + + for (&old, &new) in nums.iter().zip(right) { + window_ones -= old as u32; + window_ones += new as u32; + max_windows_ones = max_windows_ones.max(window_ones); + } + + let (left, right) = nums.split_at((n - ones) as usize); + let mut window_ones = left.iter().sum::() as u32; + let mut min_windows_ones = window_ones; + + for (&old, &new) in nums.iter().zip(right) { + window_ones -= old as u32; + window_ones += new as u32; + min_windows_ones = min_windows_ones.min(window_ones); + } + + (ones - max_windows_ones).min(min_windows_ones) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn min_swaps(nums: Vec) -> i32 { + Self::min_swaps(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +}