Problem: Balance the Boxes
You are given a row of boxes arranged from left to right.
Each box contains some number of balls.
The boxes are represented as a list of non-negative integers, where each number shows how many balls are in that box.
Your goal is to make the boxes balanced.
Balanced Rule
The boxes are considered balanced if:
- Every box has exactly the same number of balls
- You may move balls only between neighboring boxes
- Moving one ball to an adjacent box costs 1 move
- Boxes stay in place
- No balls are created or destroyed
Task
Return the minimum number of moves needed to balance all boxes.
If it is impossible to balance them, return `-1`.
Input
- A list of integers `boxes`
- `len(boxes) ≥ 1`
- Each value `≥ 0`
Output
- An integer:
- minimum number of moves, or
- `-1` if balancing is impossible
Examples
Example 1
Input:
```
[1, 2, 3]
```
Output:
```
2
```
Example 2
Input:
```
[0, 3, 0]
```
Output:
```
2
```
Example 3
Input:
```
[1, 2, 4]
```
Output:
```
-1
```
Explanation:
The total number of balls is 7, which cannot be evenly divided among 3 boxes.
Function Signature
```python
def min_moves_to_balance(boxes):
pass
```
'hacking sorcerer' 카테고리의 다른 글
| not thy beautiful (0) | 2025.12.17 |
|---|---|
| Problem Solving: Balance the Boxes (0) | 2025.12.16 |
| really beautiful (0) | 2025.12.10 |
| Problem: Valley Count in a Number Path (0) | 2025.12.02 |
| 너무 잘 만들어진 해커들의 놀이터 한국 (0) | 2025.12.01 |