Skip to content

Commit

Permalink
Add problem 1674: Minimum Moves to Make Array Complementary
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 13, 2023
1 parent 2699d4a commit 8fa4a0d
Show file tree
Hide file tree
Showing 3 changed files with 70 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 @@ -1372,6 +1372,7 @@ pub mod problem_1670_design_front_middle_back_queue;
pub mod problem_1671_minimum_number_of_removals_to_make_mountain_array;
pub mod problem_1672_richest_customer_wealth;
pub mod problem_1673_find_the_most_competitive_subsequence;
pub mod problem_1674_minimum_moves_to_make_array_complementary;
pub mod problem_1675_minimize_deviation_in_array;
pub mod problem_1678_goal_parser_interpretation;
pub mod problem_1679_max_number_of_k_sum_pairs;
Expand Down
22 changes: 22 additions & 0 deletions src/problem_1674_minimum_moves_to_make_array_complementary/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod sweep_line;

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

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

pub fn run<S: Solution>() {
let test_cases = [
((&[1, 2, 4, 3] as &[_], 4), 1),
((&[1, 2, 2, 1], 2), 2),
((&[1, 2, 1, 2], 2), 0),
];

for ((nums, k), expected) in test_cases {
assert_eq!(S::min_moves(nums.to_vec(), k), expected);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub struct Solution;

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

impl Solution {
pub fn min_moves(nums: Vec<i32>, limit: i32) -> i32 {
let limit = limit as u32 as usize;
let mut diffs = vec![0; limit * 2 + 1].into_boxed_slice();
let (left, right) = nums.split_at(nums.len() / 2);

for (&x, &y) in left.iter().zip(right.iter().rev()) {
let (x, y) = (x as u32 as usize, y as u32 as usize);
let (min, max) = if y < x { (y, x) } else { (x, y) };

diffs[min] -= 1;
diffs[min + max - 1] -= 1;
diffs[min + max] += 1;
diffs[max + limit] += 1;
}

let mut moves = nums.len() as i32;
let mut result = moves;

for &diff in &diffs[1..] {
moves += diff;
result = result.min(moves);
}

result
}
}

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

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

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

0 comments on commit 8fa4a0d

Please sign in to comment.