Skip to content

2541. Minimum Operations to Make Array Equal II 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  long long minOperations(vector<int>& nums1, vector<int>& nums2, int k) {
    if (k == 0)
      return nums1 == nums2 ? 0 : -1;

    long ans = 0;
    // the number of increments - the number of decrements
    long opsDiff = 0;

    for (int i = 0; i < nums1.size(); ++i) {
      const int diff = nums1[i] - nums2[i];
      if (diff == 0)
        continue;
      if (diff % k != 0)
        return -1;
      const int ops = diff / k;
      opsDiff += ops;
      ans += abs(ops);
    }

    return opsDiff == 0 ? ans / 2 : -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public long minOperations(int[] nums1, int[] nums2, int k) {
    if (k == 0)
      return Arrays.equals(nums1, nums2) ? 0 : -1;

    long ans = 0;
    long opsDiff = 0; // the number of increments - the number of decrements

    for (int i = 0; i < nums1.length; ++i) {
      final int diff = nums1[i] - nums2[i];
      if (diff == 0)
        continue;
      if (diff % k != 0)
        return -1;
      final int ops = diff / k;
      opsDiff += ops;
      ans += Math.abs(ops);
    }

    return opsDiff == 0 ? ans / 2 : -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def minOperations(self, nums1: list[int], nums2: list[int], k: int) -> int:
    if k == 0:
      return 0 if nums1 == nums2 else -1

    ans = 0
    opsDiff = 0  # the number of increments - number of decrements

    for num1, num2 in zip(nums1, nums2):
      diff = num1 - num2
      if diff == 0:
        continue
      if diff % k != 0:
        return -1
      ops = diff // k
      opsDiff += ops
      ans += abs(ops)

    return ans // 2 if opsDiff == 0 else -1