1422. Maximum Score After Splitting a String #1044
-
Topics: Given a string The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can leverage the hint provided by precomputing a prefix sum of ones ('1') in the string. Here's how we can break down the solution: Steps:
Let's implement this solution in PHP: 1422. Maximum Score After Splitting a String <?php
/**
* @param String $s
* @return Integer
*/
function maxScore($s) {
$n = strlen($s);
// Step 1: Precompute the number of ones up to each index
$prefixOneCount = array_fill(0, $n, 0);
$onesCount = 0;
for ($i = 0; $i < $n; $i++) {
if ($s[$i] == '1') {
$onesCount++;
}
$prefixOneCount[$i] = $onesCount;
}
// Step 2: Iterate over the string and calculate the score
$maxScore = 0;
$zeroCountLeft = 0;
// Iterate to find the maximum score for all possible splits
for ($i = 0; $i < $n - 1; $i++) { // We need at least one character on the right
if ($s[$i] == '0') {
$zeroCountLeft++;
}
// Right substring ones count
$oneCountRight = $onesCount - $prefixOneCount[$i];
// Calculate score for this split
$score = $zeroCountLeft + $oneCountRight;
$maxScore = max($maxScore, $score);
}
return $maxScore;
}
// Test cases
$s1 = "011101";
$s2 = "00111";
$s3 = "1111";
echo "Input: $s1, Output: " . maxScore($s1) . PHP_EOL; // Output: 5
echo "Input: $s2, Output: " . maxScore($s2) . PHP_EOL; // Output: 5
echo "Input: $s3, Output: " . maxScore($s3) . PHP_EOL; // Output: 3
?> Explanation:
Complexity:
Example:echo maxScore("011101"); // Output: 5
echo maxScore("00111"); // Output: 5
echo maxScore("1111"); // Output: 3 This solution is optimal and handles the problem within the constraints. |
Beta Was this translation helpful? Give feedback.
We can leverage the hint provided by precomputing a prefix sum of ones ('1') in the string. Here's how we can break down the solution:
Steps:
i
contains the number of ones ('1') up to indexi
in the string.i
, treat the substring from0
toi
as the "left" substring and fromi+1
to the end of the string as the "right" substring.