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.
Example 1:
Input: balance = [-1,2,-1]
Output: 2
Explanation:
One optimal sequence of moves is:
i = 1 to i = 0, resulting in balance = [0, 1, -1]i = 1 to i = 2, resulting in balance = [0, 0, 0]Thus, the minimum number of moves required is 2.
Example 2:
Input: balance = [4,-1,-2]
Output: 3
Explanation:
One optimal sequence of moves is:
i = 0 to i = 1, resulting in balance = [3, 0, -2]i = 0 to i = 2, resulting in balance = [2, 0, -1]i = 0 to i = 2, resulting in balance = [1, 0, 0]Thus, the minimum number of moves required is 3.
Example 3:
Input: balance = [-3,-3,5]
Output: -1
Explanation:
It is impossible to make all balances non-negative for balance = [-3, -3, 5], so the answer is -1.
Constraints:
1 <= n == balance.length <= 1000-105 <= balance[i] <= 105Problem Overview: Given a circular array, find the minimum number of moves required to make all elements equal, where each move increments or decrements an element by 1.
Approach 1: Brute Force (O(n^2))
Try every possible target value from the array. For each target, calculate the total moves needed by summing absolute differences between each element and the target. This approach is inefficient but demonstrates understanding of the problem constraints.
Approach 2: Median-based Optimization (O(n log n))
Sort the array and use the median as the target value. The median minimizes the sum of absolute deviations, reducing the total moves. This approach leverages the property that the median provides the optimal balance point in a sorted array.
Recommended for interviews: The median-based approach is expected in interviews. It shows you understand mathematical optimization and can apply sorting to reduce complexity from O(n^2) to O(n log n). Mention that brute force is a starting point but median is optimal.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force | O(n^2) | O(1) | Only for small arrays |
| Median-based | O(n log n) | O(1) | General case |
Practice Minimum Moves to Balance Circular Array II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor