All problems
0779HardArrayGreedy

Levelling The Grain Bins

Tracked in this browser only
Write code

Trains the technique from

LeetCode 517Super Washing Machines

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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