Show problems as
Classic problem #517HardArrayGreedy

Super Washing Machines

Real-world version: Levelling The Grain Bins
Tracked in this browser only
Read Super Washing Machines on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A mill has n grain bins standing in a row, and bins[i] is how many sacks bin i holds. Neighbouring bins are joined by a short conveyor; bin 0 and bin n - 1 each have a single neighbour, and the row does not wrap around.

The mill works in rounds. In one round you may choose any set of bins, and every chosen bin hands exactly one sack to one of its neighbours, either the one on its left or the one on its right. All the handovers of a round happen at the same time, so a bin may hand a sack away in the same round that it receives sacks, and a bin may receive from both sides at once. A bin can only hand over a sack it was already holding when the round began, and a bin holding no sacks cannot be chosen.

Return the least number of rounds after which every bin holds the same number of sacks, or -1 if no sequence of rounds can ever level the bins.

Examples

Example 1

Input
bins = [0,0,11,5]
Output
8

The 16 sacks level out at 4 in every bin, and a run of 8 rounds gets them there.

Example 2

Input
bins = [0,12,0]
Output
8

The 12 sacks level out at 4 in every bin, which is reached after 8 rounds.

Example 3

Input
bins = [7,0,4]
Output
-1

Eleven sacks cannot be shared evenly between three bins, so the bins can never end up level.

Example 4

Input
bins = [6,0,6]
Output
2

The share is 4 each. In one round bin 0 hands a sack right and bin 2 hands a sack left at the same time, giving [5,2,5]; repeating that gives [4,4,4].

Constraints

  • 1 <= bins.length <= 10^4
  • 0 <= bins[i] <= 10^5

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def find_min_moves(bins: list[int]) -> int:
Java
public int findMinMoves(int[] bins)