1769. Minimum Number of Operations to Move All Balls to Each Box #1083
-
Topics: You have In one operation, you can move one ball from a box to an adjacent box. Box Return an array Each Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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:
Approach:
Solution Steps:
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) {
$n = strlen($boxes);
$answer = array_fill(0, $n, 0);
// Left-to-right pass
$leftMoves = 0;
$leftCount = 0;
for ($i = 0; $i < $n; $i++) {
$answer[$i] += $leftMoves;
if ($boxes[$i] == '1') {
$leftCount++;
}
$leftMoves += $leftCount;
}
// Right-to-left pass
$rightMoves = 0;
$rightCount = 0;
for ($i = $n - 1; $i >= 0; $i--) {
$answer[$i] += $rightMoves;
if ($boxes[$i] == '1') {
$rightCount++;
}
$rightMoves += $rightCount;
}
return $answer;
}
// 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]
?> Explanation:
Example Walkthrough:Example 1:$boxes = "110";
print_r(minOperations($boxes)); Output:
Example 2:$boxes = "001011";
print_r(minOperations($boxes)); Output:
Time Complexity:
This solution efficiently computes the minimum number of operations for each box using the prefix sum technique. |
Beta Was this translation helpful? Give feedback.
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:
i
to boxj
is simplyabs(i - j)
.Approach: