Skip to content

Commit

Permalink
Add problem 2134: Minimum Swaps to Group All 1's Together II
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Feb 8, 2024
1 parent 6035b55 commit 008d7e7
Show file tree
Hide file tree
Showing 3 changed files with 71 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 @@ -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;
22 changes: 22 additions & 0 deletions src/problem_2134_minimum_swaps_to_group_all_1s_together_ii/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod sliding_window;

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

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

pub fn run<S: Solution>() {
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);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
pub struct Solution;

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

impl Solution {
pub fn min_swaps(nums: Vec<i32>) -> i32 {
let n = nums.len() as u32;
let ones = nums.iter().sum::<i32>() as u32;

let (left, right) = nums.split_at(ones as usize);
let mut window_ones = left.iter().sum::<i32>() 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::<i32>() 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>) -> i32 {
Self::min_swaps(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 008d7e7

Please sign in to comment.