Skip to main content
Back to problems
#2449
Hard Algorithms

Minimum number of operations to make arrays similar

Array Greedy Sorting
61.5% acceptance
Feb 25, 2026
450
16
You are given two positive integer arrays nums and target, of the same length . * In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and: * set nums[i] = nums[i] + 2 and set nums[j] = nums[j] - 2. Two arrays are considered to be similar if the frequency of each element is t he same. * Return the minimum number of operations required to make nums similar to targ et. The test cases are generated such that nums can always be similar to target. *

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn make_similar(nums: Vec<i32>, target: Vec<i32>) -> i64 {
    // Operations preserve parity, so match even-to-even and odd-to-odd
    let mut nums_even: Vec<i32> = nums.iter().filter(|&&x| x % 2 == 0).cloned().collect();
    let mut nums_odd: Vec<i32> = nums.iter().filter(|&&x| x % 2 == 1).cloned().collect();
    let mut tgt_even: Vec<i32> = target.iter().filter(|&&x| x % 2 == 0).cloned().collect();
    let mut tgt_odd: Vec<i32> = target.iter().filter(|&&x| x % 2 == 1).cloned().collect();
    nums_even.sort();
    nums_odd.sort();
    tgt_even.sort();
    tgt_odd.sort();
    let cost: i64 = nums_even.iter().zip(tgt_even.iter())
      .map(|(&a, &b)| (a as i64 - b as i64).abs())
      .sum::<i64>()
      + nums_odd.iter().zip(tgt_odd.iter())
      .map(|(&a, &b)| (a as i64 - b as i64).abs())
      .sum::<i64>();
    cost / 4
  }
}