Mid/SeniorArrayGreedyMath

Minimum Operations to Make Array Equal II

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.

Example 1
Inputnums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
Output2
In 2 operations, incrementing index 2 and decrementing indices 0 and 3 by k transforms nums1 into nums2, and fewer operations are impossible.
Example 2
Inputnums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
Output-1
It can be proved that it is impossible to make the two arrays equal.

Constraints

  • n == nums1.length == nums2.length
  • 2 <= n <= 10^5
  • 0 <= nums1[i], nums2[j] <= 10^9
  • 0 <= k <= 10^5

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate