KatInterview

Equalize Array Range with Bounded Transfers

Greedy & IntervalsModel answer
HardModel answerGreedy & Intervalsgreedybinary-searchmath

Last updated

Find the minimum operations to narrow an array's range below a threshold by transferring bounded amounts between pairs of elements.

You have an array of integers representing values that you want to balance.

Given:

  • An array values of length n
  • An integer maxTransfer — the maximum amount you can move in one operation
  • An integer threshold — the target range limit

You can perform operations where you select two positions i and j (they can be the same or different), pick an amount amount where 1 <= amount <= maxTransfer, then simultaneously add amount to values[i] and subtract amount from values[j].

Your objective: make the range of the array (difference between maximum and minimum values) strictly less than threshold.

Formally, after all operations: max(values) - min(values) < threshold

Find the minimum number of operations needed.

Constraints:

  • 1 <= n <= 10^5
  • 1 <= maxTransfer, threshold <= 10^9
  • -10^9 <= values[i] <= 10^9

You may assume a solution always exists for the given inputs.

Hints

Hint 1

The sum of all values never changes — each operation moves value from one position to another.

Hint 2

Binary search on the number of operations, then check if that many operations can achieve a range below the threshold.

Hint 3

For a fixed number of operations, the optimal strategy is to move all values toward a target interval of width threshold-1.