#3776
Minimum Moves to Balance Circular Array
MediumArrayGreedySortingGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
This approach leverages the fact that only one index can be negative, allowing us to balance efficiently by transferring from positive balances in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total balance; if it's negative, return -1.
- 2Step 2: Identify the index with the negative balance.
- 3Step 3: Traverse the array, transferring from positive balances to the negative index, counting moves.
solution.py9 lines
1def minMoves(balance):
2 total = sum(balance)
3 if total < 0: return -1
4 moves = 0
5 neg_index = balance.index(next(b for b in balance if b < 0))
6 for i in range(len(balance)):
7 if i != neg_index:
8 moves += max(0, balance[i])
9 return moves + -balance[neg_index]ℹ
Complexity note: Single pass through the array leads to linear time complexity.
- 1Only one negative balance simplifies the problem.
- 2Total balance must be non-negative for a solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.