Minimum Moves to Balance Circular Array Problem
Description
LeetCode Problem 3776.
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: 4
Explanation:
One optimal sequence of moves is:
- Move 1 unit from i = 1 to i = 2, resulting in balance = [5, 0, -3]
- Move 1 unit from i = 0 to i = 2, resulting in balance = [4, 0, -2]
- Move 1 unit from i = 0 to i = 2, resulting in balance = [3, 0, -1]
- Move 1 unit from i = 0 to i = 2, resulting in balance = [2, 0, 0]
Thus, the minimum number of moves required is 4.
Example 2:
Input: balance = [1,2,-5,2]
Output: 6
Explanation:
One optimal sequence of moves is:
- Move 1 unit from i = 1 to i = 2, resulting in balance = [1, 1, -4, 2]
- Move 1 unit from i = 1 to i = 2, resulting in balance = [1, 0, -3, 2]
- Move 1 unit from i = 3 to i = 2, resulting in balance = [1, 0, -2, 1]
- Move 1 unit from i = 3 to i = 2, resulting in balance = [1, 0, -1, 0]
- Move 1 unit from i = 0 to i = 1, resulting in balance = [0, 1, -1, 0]
- Move 1 unit from i = 1 to i = 2, resulting in balance = [0, 0, 0, 0]
Thus, the minimum number of moves required is 6.
Example 3:
Input: balance = [-3,2]
Output: -1
Explanation:
It is impossible to make all balances non-negative for balance = [-3, 2], so the answer is -1.
Constraints:
1 <= n == balance.length <= 10^5-10^9 <= balance[i] <= 10^9- There is at most one negative value in
balanceinitially.
Solution
Approach: Simulation
If the total is negative, no sequence of moves can make every balance non-negative, so return -1. Otherwise find the only negative balance (the minimum); if there is none, the answer is 0.
The deficit is need = -min. Moving a unit across j positions costs j moves, so the cheapest source is always the closest one. Walk outwards from the negative position: at distance j, take as much as possible from the two neighbours at that distance (left and right), add taken * j to the answer, and reduce need. Stop when need reaches 0.
Complexity: time O(n), space O(1), where n is the length of balance.
class Solution:
def minMoves(self, balance: List[int]) -> int:
if sum(balance) < 0:
return -1
mn = min(balance)
if mn >= 0:
return 0
need = -mn
i = balance.index(mn)
n = len(balance)
ans = 0
for j in range(1, n):
a = balance[(i - j + n) % n]
b = balance[(i + j - n) % n]
c1 = min(a, need)
need -= c1
ans += c1 * j
c2 = min(b, need)
need -= c2
ans += c2 * j
return ans