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
This Java solution achieves the maximum score by splitting the string iteratively while maintaining and updating count of zeros and ones to efficiently compute the score in one pass.