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 _theminimum number of operations required to make _nums1equal tonums2. If it is impossible to make them equal, return -1.
Input: nums1 =[4,3,1,4], nums2 =[1,3,7,1], k =3Output: 2Explanation: In 2 operations, we can transform nums1 to nums2.1st operation: i =2, j =0. After applying the operation, nums1 =[1,3,4,4].2nd operation: i =2, j =3. After applying the operation, nums1 =[1,3,7,1].One can prove that it is impossible to make arrays equal in fewer operations.
The operation allows us to transfer k units from one index to another. For the transformation to be possible, the total sum of differences must be zero, and each difference must be divisible by k. We count how many positive and negative k-steps are needed and match them up.
classSolution {
publiclongminOperations(int[] nums1, int[] nums2, int k) {
if (k == 0) {
for (int i = 0; i < nums1.length; ++i) {
if (nums1[i]!= nums2[i]) return-1;
}
return 0;
}
long pos = 0, neg = 0;
for (int i = 0; i < nums1.length; ++i) {
int d = nums1[i]- nums2[i];
if (d % k != 0) return-1;
if (d > 0) pos += d / k;
else neg -= d / k;
}
return pos == neg ? pos : -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funminOperations(nums1: IntArray, nums2: IntArray, k: Int): Long {
if (k ==0) {
for (i in nums1.indices) {
if (nums1[i] != nums2[i]) return -1 }
return0 }
var pos = 0Lvar neg = 0Lfor (i in nums1.indices) {
val d = nums1[i] - nums2[i]
if (d % k !=0) return -1if (d > 0) pos += d / k
else neg -= d / k
}
returnif (pos == neg) pos else -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defminOperations(self, nums1: list[int], nums2: list[int], k: int) -> int:
if k ==0:
return0if nums1 == nums2 else-1 pos: int =0 neg: int =0for a, b in zip(nums1, nums2):
d: int = a - b
if d % k !=0:
return-1if d >0:
pos += d // k
else:
neg -= d // k
return pos if pos == neg else-1