Minimum Moves to Balance Circular Array II Problem
Description
LeetCode Problem 4004.
You are given a circular array balance of length n, where balance[i] is the net balance of person i.
In one move, a person can transfer exactly 1 unit of balance to either their left or right neighbor.
Return the minimum number of moves required so that every person has a non-negative balance. If it is impossible, return -1.
Example 1:
Input: balance = [-1,2,-1]
Output: 2
Explanation:
One optimal sequence of moves is:
- Move 1 unit from i = 1 to i = 0, resulting in balance = [0, 1, -1]
- Move 1 unit from i = 1 to i = 2, resulting in balance = [0, 0, 0]
Thus, the minimum number of moves required is 2.
Example 2:
Input: balance = [4,-1,-2]
Output: 3
Explanation:
One optimal sequence of moves is:
- Move 1 unit from i = 0 to i = 1, resulting in balance = [3, 0, -2]
- Move 1 unit from i = 0 to i = 2, resulting in balance = [2, 0, -1]
- Move 1 unit from i = 0 to i = 2, resulting in balance = [1, 0, 0]
Thus, the minimum number of moves required is 3.
Example 3:
Input: balance = [-3,-3,5]
Output: -1
Explanation:
It is impossible to make all balances non-negative for balance = [-3, -3, 5], so the answer is -1.
Constraints:
1 <= n == balance.length <= 1000-10^5 <= balance[i] <= 10^5
Solution
Approach: Minimum Cost Flow
If the sum of all balances is negative, nobody can fix the deficit, so return -1.
Otherwise model it as a minimum cost flow:
- add a source
sand a sinkt; - for each person with a positive balance (a surplus), add an edge
s -> iwith capacitybalance[i]and cost0; - for each person with a negative balance (a deficit), add an edge
i -> twith capacity-balance[i]and cost0; - for each person
i, add edges to both circular neighbors with unlimited capacity and cost1, since moving one unit to a neighbor takes one move.
Let D be the total deficit. The answer is the minimum cost of sending D units from s to t. Because the cycle connects everybody in both directions and the total balance is non-negative, all D units can always be delivered.
Solve it with successive shortest paths: find a cheapest augmenting path with SPFA (a queue-based Bellman-Ford), push as much flow as its bottleneck allows, and repeat until D units are sent. The bottleneck is either a source or sink edge (which becomes saturated) or a reverse cycle edge, so the number of augmentations does not depend on the size of the balances. On a unit-cost cycle SPFA behaves almost like BFS, which keeps this fast for n <= 1000.
The Python version solves the same problem without a flow graph, because the flow is slow in Python. Let f[i] be the net number of units sent over the edge from i to i + 1 (negative means the other direction). Person i ends with balance[i] - f[i] + f[i - 1], which must be at least 0, and the cost is the sum of |f[i]|. Fix t = f[n - 1]: the remaining values form a chain where f[i] <= f[i - 1] + balance[i], and the best cost of the chain as a function of the last value is convex and piecewise linear. Slope trick keeps it in a heap: each step takes a suffix minimum, shifts by balance[i], and adds |x|. The total cost is convex in t, and in an optimal solution |t| is at most the total deficit, so a binary search on the sign of cost(t + 1) - cost(t) finds the best t. That takes O(n log n log D) time, where D is the total deficit.
Complexity: about O(n^2) in practice (worst case O(n^3) with SPFA, or O(n^2 log n) using Dijkstra with potentials), space O(n).
import heapq
class Solution:
def minMoves(self, balance: List[int]) -> int:
n = len(balance)
if sum(balance) < 0:
return -1
deficit = sum(-x for x in balance if x < 0)
if deficit == 0:
return 0
# f[i]: net units sent over the edge i -> i + 1 (negative means the other way).
# Person i ends with balance[i] - f[i] + f[i - 1] >= 0, and the cost is the sum of |f[i]|.
# Fix t = f[n - 1] and solve the chain f[0..n-2] with slope trick; the cost is convex in t.
def cost(t: int) -> int:
# h(x): best cost of f[0..i] with f[i] = x, kept after taking its suffix minimum,
# as low + sum of (x - r) over the breakpoints r < x, on the domain x <= cap
low = 0
cap = t
shift = 0 # every breakpoint stored in right is shifted by this much
right = []
for i in range(n - 1):
b = balance[i]
shift += b
cap += b
# add |x| = max(0, x) + max(0, -x)
heapq.heappush(right, -shift)
r = min(right[0] + shift, cap)
if r < 0:
low -= r
heapq.heappush(right, -shift)
if right[0] + shift <= cap:
heapq.heappop(right)
# the part left of the minimum is dropped by the next suffix minimum
z = t - balance[n - 1] # f[n - 1] = t needs f[n - 2] >= z
total = low
for r in right:
if r + shift < z:
total += z - r - shift
return abs(t) + total
lo, hi = -deficit, deficit
while lo < hi:
mid = (lo + hi) // 2
if cost(mid + 1) >= cost(mid):
hi = mid
else:
lo = mid + 1
return cost(lo)