#2541

Minimum Operations to Make Array Equal II

Medium
ArrayMathGreedyGreedyMath
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we can only increment and decrement by k. By calculating the total excess and deficit, we can determine the minimum number of operations needed without brute-forcing through pairs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total excess (sum of positive differences) and deficit (sum of negative differences) between nums1 and nums2.
  2. 2Step 2: If the total excess is not equal to the total deficit, return -1 (impossible to balance).
  3. 3Step 3: Return the total excess divided by k, as each operation can adjust both excess and deficit by k.
solution.py13 lines
1def minOperations(nums1, nums2, k):
2    if k == 0:
3        return -1 if nums1 != nums2 else 0
4    excess = 0
5    deficit = 0
6    for a, b in zip(nums1, nums2):
7        if a > b:
8            excess += (a - b)
9        elif a < b:
10            deficit += (b - a)
11    if excess != deficit:
12        return -1
13    return excess // k

Complexity note: The complexity is O(n) because we only need a single pass through the arrays to calculate the excess and deficit.

  • 1You can only balance the arrays if the total excess equals the total deficit.
  • 2The operations can be optimized by calculating the total differences instead of simulating each operation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.