A row of washing machines each holds some number of dresses, given left to right in the array machines. In one move you pick any group of machines, and each picked machine passes one of its dresses to the machine directly left or right of it. All the picked machines act at the same time.
Return the fewest moves that leave every machine with the same number of dresses. If that can never happen, return -1.
Example 1
Input: machines = [1, 6, 0, 1] Output: 4 Why: machine 1 has 4 extra and gives one per move
2 more examples and the constraints
Example 2
Input: machines = [5, 5, 0, 0, 0] Output: 6 Why: 6 dresses must cross the gap after machine 1
Example 3
Input: machines = [3, 0, 2, 0] Output: -1 Why: 5 dresses cannot split evenly over 4 machines
Constraints
- 1 ≤ machines.length ≤ 10,000
- 0 ≤ machines[i] ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Prefix sums, flow per gapO(n)
- One pass with a running balanceO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Memory for 10,000 machines | Verdict |
|---|---|---|---|
| Prefix sums, flow per gap | O(n) | Passes; stores n prefix sums | |
| One pass with a running balance | O(n) | Best; a few counters |
n = the number of machines.
Edge cases to test
- Total does not split. If sum(machines) is not a multiple of n, no number of moves helps: return -1.
- One machine. It is already equal to itself: 0 moves.
- Giver in the middle. In [0, 6, 0] each gap carries only 2, but the middle machine has 4 extra and gives one per move: 4.
- Big sums. 10,000 machines of 100,000 dresses sum to 10⁹. That fits in a 32-bit int, but
avg * (i + 1)style products are safer in a 64-bit type.
Common mistakes
- Using
abs(m - avg)for a machine: a short machine can receive from both sides in one move, so only the extra counts. - Adding the gap flows together instead of taking their maximum: moves run in parallel.
- Forgetting the divisibility check before computing the average.
How to talk through it
- 1Clarify. In one move can every machine pass a dress at the same time? Only to a direct neighbour?
- 2Check it is possible. The total must divide by n, or return -1.
- 3Find lower bounds. Each gap must carry the difference between what the left side has and what it needs, one dress per move. Each machine with extra dresses gives at most one per move.
- 4Claim the bound is reached. The answer is the largest bound, and a running balance gives every gap flow in one pass.
- 5Test out loud. Run [0, 6, 0], [5, 5, 0, 0, 0] and an uneven total.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?