Equalize Array Range with Bounded Transfers
Greedy & IntervalsModel answerLast 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
valuesof lengthn - 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^51 <= 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines greedy reasoning with binary search. The key insight is that operations preserve the total sum — we're redistributing value, not creating or destroying it.
Key Observations
-
Invariant: The sum of all array elements remains constant. Each operation transfers value between positions.
-
Target interval: To achieve
max - min < threshold, we need all values within some interval[L, L + threshold - 1]. -
Optimal target: The best target interval should be centered around the mean (or adjusted based on current distribution) to minimize total transfer distance.
-
Binary search: The minimum operations is monotonic — if we can succeed in
koperations, we can succeed ink+1. This suggests binary search on the answer.
Algorithm
Step 1: Binary search on operation count
Set bounds: left = 0, right = (max - min) / 1 (upper bound on operations needed).
Step 2: Feasibility check for k operations
Given k operations with capacity maxTransfer each, we have total capacity k * maxTransfer.
We need to determine if we can move values into some interval of width threshold - 1.
Step 3: Choose optimal target interval
For a candidate interval [targetMin, targetMin + threshold - 1]:
- Values below
targetMinneed to be increased - Values above
targetMin + threshold - 1need to be decreased - Calculate the total upward and downward transfer needed
The optimal targetMin minimizes the maximum of (total upward transfer, total downward transfer), since we can only transfer as much as the limiting direction allows.
Step 4: Greedy validation
For each value:
- If
values[i] < targetMin: needstargetMin - values[i]units transferred in - If
values[i] > targetMin + threshold - 1: needsvalues[i] - (targetMin + threshold - 1)units transferred out
Sum all inward and outward needs. Both must be ≤ k * maxTransfer, and they must be equal (since total sum is preserved).
Implementation Strategy
def minOperations(values, maxTransfer, threshold):
n = len(values)
if max(values) - min(values) < threshold:
return 0
def canAchieve(ops):
capacity = ops * maxTransfer
# Try different target intervals
# Optimization: binary search or sweep over reasonable targetMin values
# For simplicity, try intervals starting from min to max
minVal, maxVal = min(values), max(values)
# The optimal target should be checked systematically
# Key insight: try targetMin at each distinct value position
candidates = sorted(set(values))
for targetMin in candidates:
targetMax = targetMin + threshold - 1
deficit = 0 # total amount needed to move up
surplus = 0 # total amount needed to move down
for v in values:
if v < targetMin:
deficit += targetMin - v
elif v > targetMax:
surplus += v - targetMax
# Check if we can perform the transfers
if deficit == surplus and deficit <= capacity:
return True
return False
# Binary search on number of operations
left, right = 0, (max(values) - min(values)) * n
result = right
while left <= right:
mid = (left + right) // 2
if canAchieve(mid):
result = mid
right = mid - 1
else:
left = mid + 1
return result
Complexity Analysis
-
Time: O(n log(range) · n) where range is the initial max - min. The binary search takes O(log(range · n)) iterations, and each feasibility check scans the array O(n) times for O(n) candidate intervals.
-
Space: O(n) for storing candidate target positions.
Optimization
For large inputs, instead of trying every distinct value as targetMin, we can:
- Binary search on targetMin itself
- Use the median or mean-based heuristics
- Recognize that the optimal interval often aligns with clustering in the data
Common Mistakes
-
Forgetting sum invariant: You cannot arbitrarily set all values to the same number if their sum doesn't allow it.
-
Off-by-one in threshold: The requirement is strictly less than threshold, so the valid range width is
threshold - 1. -
Wrong binary search bounds: The upper bound should account for worst-case transfer needs.
-
Ignoring balance: Total upward movement must equal total downward movement.
Example Walkthrough
Input: values = [1, 5, 10], maxTransfer = 2, threshold = 5
Current range: 10 - 1 = 9, need < 5.
Try 2 operations (capacity = 4):
- Target interval
[5, 8] - Value 1 needs +4 → requires 4 units in
- Value 10 needs -2 → provides 2 units out
- Imbalance: cannot work
Try 3 operations (capacity = 6):
- Target interval
[4, 7] - Value 1 needs +3, value 10 needs -3
- Total 6 capacity, need 3: works!
Answer: 3 operations.