Given a string s
of zeros and ones, we want to split the string into two non-empty substrings left
and right
such that the score is maximized. The score of a split is defined as the number of ‘0’s in the left substring plus the number of ‘1’s in the right substring.
Return the maximum score we can achieve from any possible split of the string s
.
s
?
left
and right
must be non-empty.If s = "011101" , then splitting it at different positions like “0 |
11101”, “01 | 1101”, etc., and computing the score will help validate the implementation. |
max_score
to track the maximum score found.left_zeros
to count ‘0’s in the left substring.right_ones
to count ‘1’s in the right substring.right_ones
counter.max_score
.len(s) - 1
to ensure non-empty substrings.Here’s the implementation in Python:
def maxScore(s: str) -> int:
# Initial count of '1's in the entire string
right_ones = s.count('1')
left_zeros = 0
max_score = 0
# Traverse the string, but stop at second last character to ensure non-empty right substring
for i in range(len(s) - 1):
if s[i] == '0':
left_zeros += 1
else:
right_ones -= 1
# Calculate score for the current partition
current_score = left_zeros + right_ones
max_score = max(max_score, current_score)
return max_score
# Example usage
print(maxScore("011101")) # Output: 5
print(maxScore("00111")) # Output: 5
print(maxScore("1111")) # Output: 3
This code correctly follows our outlined strategy and calculates the maximum score possible after splitting the string at any given position.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?