Minimum Operations to Make Array Equal II Problem
Description
LeetCode Problem 2541.
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
iandjand incrementnums1[i]bykand decrementnums1[j]byk. In other words,nums1[i] = nums1[i] + kandnums1[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.
Example 1:
Input: nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
Output: 2
Explanation: In 2 operations, we can transform nums1 to nums2.
1^st operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].
2^nd 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.
Example 2:
Input: nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
Output: -1
Explanation: It can be proved that it is impossible to make the two arrays equal.
Constraints:
n == nums1.length == nums2.length2 <= n <= 10^50 <= nums1[i], nums2[j] <= 10^90 <= k <= 10^5
Solution
Approach: Single Pass
One operation adds k to one element and subtracts k from another, so the total never changes and each position's difference must be a multiple of k.
For each index with x = nums1[i] and y = nums2[i]:
- if
x == y, nothing to do; - if
k == 0orx - yis not divisible byk, return-1; - otherwise
t = (x - y) / kis how many steps this position must go down (whent > 0) or up (whent < 0).
Add the downward steps to b and the upward steps to a. Every operation pairs one up-step with one down-step, so the answer is a if a == b, and -1 otherwise.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:
a = b = 0
for x, y in zip(nums1, nums2):
if x == y:
continue
if k == 0 or (x - y) % k:
return -1
t = (x - y) // k
if t < 0:
a += -t
else:
b += t
return a if a == b else -1