1769. Minimum Number of Operations to Move All Balls to Each Box
Difficulty: Medium
Topics: Array, String, Prefix Sum
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith 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 box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.
Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.
Each answer[i] is calculated considering the initial state of the boxes.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We can use a prefix sum approach that allows us to calculate the minimum number of operations needed to move all balls to each box without explicitly simulating each operation.
Let's implement this solution in PHP: 1769. Minimum Number of Operations to Move All Balls to Each Box
<?php /** * @param String $boxes * @return Integer[] */ function minOperations($boxes) { ... ... ... /** * go to ./solution.php */ } // Example usage: $boxes = "110"; print_r(minOperations($boxes)); // Output: [1,1,3] $boxes = "001011"; print_r(minOperations($boxes)); // Output: [11,8,5,4,3,4] ?> <h3> Explanation: </h3> <ol> <li> <strong>Left-to-right pass</strong>: We calculate the total number of operations required to bring all balls from the left side to the current box. For each ball found ('1'), we update the total number of moves.</li> <li> <strong>Right-to-left pass</strong>: Similar to the left-to-right pass, but we calculate the number of operations to move balls from the right side to the current box.</li> <li>The total number of operations for each box is the sum of moves from the left and right passes.</li> </ol> <h3> Example Walkthrough: </h3> <h4> Example 1: </h4> <pre class="brush:php;toolbar:false">$boxes = "110"; print_r(minOperations($boxes));
Output:
Array ( [0] => 1 [1] => 1 [2] => 3 )
$boxes = "001011"; print_r(minOperations($boxes));
Output:
Array ( [0] => 11 [1] => 8 [2] => 5 [3] => 4 [4] => 3 [5] => 4 )
This solution efficiently computes the minimum number of operations for each box using the prefix sum technique.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Minimum Number of Operations to Move All Balls to Each Box. For more information, please follow other related articles on the PHP Chinese website!