[LeetCode] Minimum Operations to Make Array Equal II

2540. Minimum Common Value

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. In other words, nums1[i] = nums1[i] + k and nums1[j] = nums1[j] - 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
long long minOperations(vector<int>& nums1, vector<int>& nums2, int k) {
long long plus = 0, minus = 0;
if(k == 0) {
for(int i = 0; i < nums1.size(); i++) {
if(nums1[i] != nums2[i]) return -1;
}
return 0;
}
for(int i = 0; i < nums1.size(); i++) {
if(nums1[i] == nums2[i]) continue;
long long diff = nums1[i] - nums2[i];
if(diff % k) return -1;
if(diff > 0) plus += diff / k;
else minus += -diff / k;
}
if(plus == minus) return plus;
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/21/PS/LeetCode/minimum-operations-to-make-array-equal-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.