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.
Example 1
Input
balance = [5,1,-4]Output
4An optimal sequence transfers 1 unit from index 1 to index 2 and 3 units from index 0 to index 2, requiring 4 moves total.
Example 2
Input
balance = [1,2,-5,2]Output
6An optimal sequence uses nearby positive balances to cover the negative value at index 2 in 6 moves total.
Constraints
- 1 <= n == balance.length <= 10^5
- -10^9 <= balance[i] <= 10^9
- There is at most one negative value in balance initially.