shelves[i] is the number of boxes on shelf i. You want every shelf to hold the same number of boxes.
Boxes move in rounds. In one round you pick any number of shelves (at least one), and each picked shelf simultaneously passes exactly one box to a neighbouring shelf, left or right.
Return the fewest rounds needed to level all the shelves. If it cannot be done, return −1.shelves=[4, 0, 2] → 2
Each shelf needs 2 boxes. Round 1: the first shelf hands a box to the second → [3, 1, 2]. Round 2: again → [2, 2, 2]. The answer is 2.
shelves=[0, 0, 8, 0] → 6
Each shelf needs 2 boxes. The third shelf has to give away 6 of them but can pass only one per round, so at least 6 rounds are needed, and 6 are enough.
shelves=[1, 2] → -1
3 boxes cannot be split evenly between 2 shelves, so the answer is −1.
shelves=[4, 0, 2]
2
Run checks the first 3 tests in your browser. Submit checks all 56 tests on the server, hidden ones included.