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
Inputbalance = [5,1,-4]
Output4
An 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
Inputbalance = [1,2,-5,2]
Output6
An 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.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate