[LeetCode] Minimum Moves to Balance Circular Array

3776. Minimum Moves to Balance Circular Array

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.

Note: You are guaranteed that at most 1 index has a negative balance initially.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long minMoves(vector<int>& balance) {
if(accumulate(begin(balance), end(balance), 0ll) < 0) return -1;
long long res = 0, at = min_element(begin(balance), end(balance)) - begin(balance), n = balance.size(), l = at - 1, r = at + 1, cost = 1;
while(balance[at] < 0) {
if(l == -1) l = n - 1;
if(r == n) r = 0;
long long req = -balance[at];
long long op = min(req, 0ll + balance[l] + balance[r]);
res += op * cost;
balance[at] += op;
l--,r++,cost++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-moves-to-balance-circular-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.