Maximum Score After Splitting a String
Here’s a way to calculate the maximum score after splitting the given string into two non-empty substrings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| class Solution:
def maxScore(self, s: str) -> int:
# Calculate the total number of ones in the string
total_ones = s.count('1')
# Initialize variables for the score, maximum score, and number of zeros
score = 0
max_score = 0
num_zeros = 0
# Iterate through the string, except the last character
for i in range(len(s) - 1):
# If the character is '0', increment the number of zeros
if s[i] == '0':
num_zeros += 1
else:
# If the character is '1', decrement the total number of ones
total_ones -= 1
# Calculate the current score
score = num_zeros + total_ones
# Update the maximum score if the current score is higher
if score > max_score:
max_score = score
return max_score
|
This code first calculates the total number of ones in the given string and initializes variables to keep track of the score, maximum score, and number of zeros encountered so far.
Then, it iterates through the string, excluding the last character, and updates the score based on the current character being a ‘0’ or ‘1’. It also updates the maximum score if the current score is higher than the previous maximum score.
Finally, it returns the maximum score found.
The time complexity of this solution is O(n), and the space complexity is O(1), where n is the length of the input string.