292. Minimum Moves to Gather Balls in Boxes
Minimum Moves to Gather Balls in Boxes
You are given n boxes described by a binary string boxes of length n. If boxes[i] is '1', box i contains one ball. If it is '0', the box is empty.
In one move, you may transfer one ball from its current box to a neighboring box. Two boxes at indices i and j are neighbors when Math.abs(i - j) == 1. Multiple balls may occupy the same box.
For each box, find the minimum number of moves needed to gather every ball in that box. Evaluate each destination box separately using the original arrangement of balls.

Method Signature

List<Integer> minMoves(String boxes)
  • boxes represents the initial arrangement of balls.
  • Return a list of length n, where the value at index i is the minimum number of moves needed to gather all balls in box i.
  • Return the results in increasing box-index order.

Constraints

  • n == boxes.length()
  • 1 <= n <= 2,000
  • Every character in boxes is either '0' or '1'.

Examples

Example 1

Input: boxes = "10101"
Method call: minMoves(boxes)
Output: [6, 5, 4, 5, 6]
The balls begin in boxes 0, 2, and 4. Gathering them in box 2 requires 2 + 0 + 2 = 4 moves.

Example 2

Input: boxes = "0100"
Method call: minMoves(boxes)
Output: [1, 0, 1, 2]
There is one ball in box 1, so each result is the distance between box 1 and the corresponding destination box.


Please use Laptop/Desktop or any other large screen to add/edit code.