#2541

Minimum Operations to Make Array Equal II

expert · 1090 · lc medium +32 · verified · 33.1% accepted · 443 likes · top 11%

Description

You have equal-length integer arrays nums1 and nums2 and an integer k. In each operation you may pick two indices i and j and set nums1[i] = nums1[i] + k and nums1[j] = nums1[j] - k. Return the minimum number of operations to make nums1 element-wise equal to nums2, or -1 if it is impossible.

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.
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.

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.

Code

1
2
3