#2541
Medium Algorithms Minimum operations to make array equal ii
Array Math Greedy
33.0% acceptance
Feb 25, 2026
442
26
You are given two integer arrays nums1 and nums2 of equal length n and an integer k.
You can perform the following operation on nums1:
Choose two indexes i and j and increment nums1[i] by k and decrement nums1[j] by k.
nums1 is said to be equal to nums2 if for all indices i such that 0 <= i < n,
nums1[i] == nums2[i].
Return the minimum number of operations required to make nums1 equal to nums2.
If it is impossible to make them equal, return -1.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_operations(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> i64 {
if k == 0 {
return if nums1 == nums2 { 0 } else { -1 };
}
let mut pos_sum = 0i64;
let mut neg_sum = 0i64;
for (&a, &b) in nums1.iter().zip(nums2.iter()) {
let diff = (b - a) as i64;
if diff % k as i64 != 0 {
return -1;
}
let d = diff / k as i64;
if d > 0 {
pos_sum += d;
} else {
neg_sum += -d;
}
}
if pos_sum != neg_sum {
return -1;
}
pos_sum
}
}