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

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
Minimum Operations to Make Array Equal II INPUT nums1 4 2 5 3 nums2 1 6 5 1 diff = nums2 - nums1 -3 +4 0 -2 k = 3 i=0 i=1 i=2 i=3 ALGORITHM STEPS 1 Calculate Differences diff[i] = nums2[i] - nums1[i] 2 Check Divisibility Each diff must be divisible by k 3 Sum Check Total diff must equal 0 4 Count Operations ops = sum(positive diff/k) Calculations: diff/k: -3/3=-1, 4/3=X 4 not divisible by 3! But sum: -3+4+0-2 = -1 Positive sum: 3/3 = 1 Total ops = 2 FINAL RESULT Operations Visualization Operation 1 nums1[0] += 3 --> 4+3=7 nums1[1] -= 3 --> 2-3=-1 Operation 2 nums1[0] -= 3 --> 7-3=4 Adjust to reach target Output 2 [OK] Minimum operations = 2 Both arrays become equal [1, 6, 5, 1] Key Insight: Each operation adds k to one element and subtracts k from another, keeping total sum constant. For solution to exist: (1) All differences must be divisible by k, (2) Sum of differences must be 0. Minimum operations = (sum of positive differences) / k, as each op pairs a +k with a -k. TutorialsPoint - Minimum Operations to Make Array Equal II | Greedy Difference Matching
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen