1422. Maximum Score After Splitting a String
https://leetcode.com/problems/maximum-score-after-splitting-a-string/
Given a string s
of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
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:
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
Example 3:
Input: s = "1111"
Output: 3
Constraints:
2 <= s.length <= 500
The string
s
consists of characters '0' and '1' only.
由01组成的数组问左右划分后使得左边的count(l_0)和右边的count(l_1)的和最大(要求左右至少有一个元素),这个argmax(sum(count(l_0) + count(l_1)))是多少。直观的解法是前后各遍历一遍记录下以i点分界前面的0和后面的1的个数。实际只需要从头遍历一遍,以i为左边最后一个元素,记录当前遇到的0和1的个数,所求为argmax(count(l_0) + count(r_1)) = argmax(count(l_0) - count(l_1) + count(total_1)) ,因此遍历时再比较当前是否argmax(count(l_0) - count(l_1))。
class Solution:
def maxScore(self, s: str) -> int:
zs = os = 0
ldiff = -float('inf')
for i, c in enumerate(s):
if c == '0':
zs += 1
else:
os += 1
if i != len(s) - 1:
ldiff = max(ldiff, zs - os)
return ldiff + os
Last updated
Was this helpful?