Minimum Number of Operations to Move All Balls to Each Box
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:
- Input: boxes = "110"
- Output: [1,1,3]
-
Explanation: The answer for each box is as follows:
- First box: you will have to move one ball from the second box to the first box in one operation.
- Second box: you will have to move one ball from the first box to the second box in one operation.
- 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]
Constraints:
- n == boxes.length
- 1 <= n <= 2000
- boxes[i] is either '0' or '1'.
Hint:
- If you want to move a ball from box i to box j, you'll need abs(i-j) moves.
- To move all balls to some box, you can move them one by one.
- For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
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.
Key Observations:
- The number of moves required to move a ball from box i to box j is simply abs(i - j).
- We can calculate the total number of moves to move all balls to a particular box by leveraging the positions of the balls and a running total of operations.
- By calculating moves from left to right and right to left, we can determine the result in two passes.
Approach:
- Left-to-Right Pass: In this pass, calculate the number of moves to bring all balls to the current box starting from the left.
- Right-to-Left Pass: In this pass, calculate the number of moves to bring all balls to the current box starting from the right.
- Combine the results of both passes to get the final result for each box.
Solution Steps:
- Start by iterating through the boxes string and counting how many balls are to the left and to the right of each box.
- During the iteration, calculate the number of moves required to bring all balls to the current box using both the left and right information.
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 )
Example 2:
$boxes = "001011"; print_r(minOperations($boxes));
Output:
Array ( [0] => 11 [1] => 8 [2] => 5 [3] => 4 [4] => 3 [5] => 4 )
Time Complexity:
- The solution runs in O(n) time because we iterate over the boxes string twice (once for the left-to-right pass and once for the right-to-left pass).
- The space complexity is O(n) because we store the answer array to hold the results.
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:
- GitHub
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
