Sponsored
Sponsored
This approach involves calculating the cumulative sum of zeros from the start up to each point, and ones from the end at each point. For each possible split, compute the score using these pre-computed sums and track the maximum score.
Time Complexity: O(n), where n is the length of the string since it scans the string once.
Space Complexity: O(1), as it only uses variables for counting.
1def max_score(s: str) -> int:
2 total_ones = s.count('1')
3 left_zeros = 0
4 right_ones = total_ones
5 max_score = 0
6 for i in range(len(s) - 1):
7 if s[i] == '0':
8 left_zeros += 1
9 else:
10 right_ones -= 1
11 max_score = max(max_score, left_zeros + right_ones)
12 return max_score
13
14print(max_score("011101")) # Output: 5
15print(max_score("00111")) # Output: 5
16print(max_score("1111")) # Output: 3
The function evaluates scores at each possible split within the string by leveraging the count of zeros in the left substring and ones in the right substring. The approach efficiently computes scores by adjusting counts incrementally.
This approach derives the solution in a single pass by calculating the score dynamically using prefix sum techniques. At each character, it updates the possible maximum score by subtracting a prefix count incrementally.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), since it uses only a few variables.
1
class ProgramSinglePass {
public static int MaxScoreSinglePass(string s) {
int leftZeros = 0, rightOnes = 0, maxScore = 0;
foreach (char ch in s) {
if (ch == '1') rightOnes++;
}
for (int i = 0; i < s.Length - 1; i++) {
if (s[i] == '0') leftZeros++;
else rightOnes--;
maxScore = Math.Max(maxScore, leftZeros + rightOnes);
}
return maxScore;
}
static void Main(string[] args) {
Console.WriteLine(MaxScoreSinglePass("011101")); // Output: 5
Console.WriteLine(MaxScoreSinglePass("00111")); // Output: 5
Console.WriteLine(MaxScoreSinglePass("1111")); // Output: 3
}
}
This C# code finds the maximum possible score by assessing each possible split point and using running counts of zeros and ones in a single linear pass.