Minimum Operations to Make Array Equal II - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,7,5], nums2 = [4,1,8], k = 3
›
Output:
2
💡 Note:
diff = [3,-6,3]. Sum = 0, all divisible by 3. Need to transfer 3+3=6 units in steps of 3, so 2 operations: add 3 to index 0 and subtract from index 1, then add 3 to index 2 and subtract from index 1.
Example 2 — Possible Case
$
Input:
nums1 = [0,5,4], nums2 = [4,1,4], k = 4
›
Output:
1
💡 Note:
diff = [4,-4,0]. Sum = 0, all divisible by 4. Need 1 operation: add 4 to index 0 and subtract 4 from index 1.
Example 3 — Valid Transformation
$
Input:
nums1 = [3], nums2 = [3], k = 2
›
Output:
0
💡 Note:
Arrays are already equal, no operations needed.
Constraints
- n == nums1.length == nums2.length
- 1 ≤ n ≤ 105
- 0 ≤ nums1[i], nums2[i] ≤ 109
- 0 ≤ k ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code