1769. Minimum Number of Operations to Move All Balls to Each Box
- You have
n
boxes. You are given a binary stringboxes
of lengthn
, whereboxes[i]
is'0'
if theith
box is empty, and'1'
if it contains one ball. - In one operation, you can move one ball from a box to an adjacent box. Box
i
is adjacent to boxj
ifabs(i - j) == 1
. Note that after doing so, there may be more than one ball in some boxes. - Return an array
answer
of sizen
, whereanswer[i]
is the minimum number of operations needed to move all the balls to theith
box. - Each
answer[i]
is calculated considering the initial state of the boxes.
Example 1
Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
Example 2
Input: boxes = "001011"
Output: [11,8,5,4,3,4]
Method 1
【O(n) time | O(n) space】
package Leetcode.Array;
/**
* @author zhengxingxing
* @date 2025/01/06
*/
public class MinimumNumberOfOperationsToMoveAllBallsToEachBox {
public static int[] minOperations(String boxes) {
int n = boxes.length();
int[] answer = new int[n];
int ballsOnLeft = 0;
int operationsFormLeft = 0;
for (int i = 0; i < n; i++) {
answer[i] += operationsFormLeft;
ballsOnLeft += boxes.charAt(i) == '1' ? 1 : 0;
operationsFormLeft += ballsOnLeft;
}
int ballsOnRight = 0;
int operationsFormRight = 0;
for (int i = n - 1; i >= 0; i--) {
answer[i] += operationsFormRight;
ballsOnRight += boxes.charAt(i) == '1' ? 1 : 0;
operationsFormRight += ballsOnRight;
}
return answer;
}
public static void main(String[] args) {
// 测试用例1
String boxes1 = "110";
int[] result1 = minOperations(boxes1);
System.out.print("测试用例1结果: ");
for (int num : result1) {
System.out.print(num + " ");
}
System.out.println();
// 测试用例2
String boxes2 = "001011";
int[] result2 = minOperations(boxes2);
System.out.print("测试用例2结果: ");
for (int num : result2) {
System.out.print(num + " ");
}
}
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: