3228. Maximum Number of Operations to Move Ones to the End #2415
-
|
Topics: You are given a binary string You can perform the following operation on the string any number of times:
Return the maximum number of operations that you can perform. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to determine the maximum number of operations that can be performed on a binary string. Each operation involves moving a '1' to the right until it reaches the end of the string or another '1'. The goal is to maximize the number of such operations. Approach:
Let's implement this solution in PHP: 3228. Maximum Number of Operations to Move Ones to the End <?php
/**
* @param String $s
* @return Integer
*/
function maxOperations($s) {
$n = strlen($s);
$positions = [];
for ($i = 0; $i < $n; $i++) {
if ($s[$i] == '1') {
$positions[] = $i;
}
}
$k = count($positions);
if ($k == 0) {
return 0;
}
$d = array_fill(0, $k, 0);
for ($i = 0; $i < $k - 1; $i++) {
$d[$i] = $positions[$i+1] - $positions[$i] - 1;
}
$d[$k-1] = $n - $positions[$k-1] - 1;
$m = array_fill(0, $k, 0);
$m[$k-1] = min($d[$k-1], 1);
for ($i = $k - 2; $i >= 0; $i--) {
$m[$i] = min($d[$i], 1) + $m[$i+1];
}
return array_sum($m);
}
// Test cases
// Example 1
echo maxOperations("1001101") . PHP_EOL; // Output: 4
// Example 2
echo maxOperations("00111") . PHP_EOL; // Output: 0
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to determine the maximum number of operations that can be performed on a binary string. Each operation involves moving a '1' to the right until it reaches the end of the string or another '1'. The goal is to maximize the number of such operations.
Approach: