Split a binary string into two non-empty parts to maximize the number of 0s on the left plus the number of 1s on the right.
Maximum Score After Splitting a String
You are given a binary string s consisting only of '0' and '1'.
Choose one split point so that s is divided into two non-empty parts:
- a left part
s[0..i] - a right part
s[i+1..n-1]
The score of a split is:
- the number of
'0'characters in the left part - plus the number of
'1'characters in the right part
Return the maximum possible score over all valid split positions.
The split must leave at least one character on each side.
Input Format
- A single binary string
s. scontains only characters'0'and'1'.- You must split it into two non-empty substrings.
Output Format
- Return one integer: the maximum achievable score among all valid splits.
Constraints
2 <= s.lengths[i]is either'0'or'1'- The split point must be between two characters.
Example 1
Input
s = "011101"
Output
5
Explanation
One optimal split is 0111 | 01. The left part has 1 zero, and the right part has 2 ones, for a total score of 3. A better split is 0 | 11101, where the left has 1 zero and the right has 4 ones, giving 5.
Example 2
Input
s = "00111"
Output
5
Explanation
Splitting after the second character gives 00 | 111. The left part has 2 zeros and the right part has 3 ones, so the score is 5.
Show 1 more example
Example 3
Input
s = "1111"
Output
3
Explanation
Any valid split has 0 zeros on the left and some ones on the right. Splitting after the first character yields score 3, which is maximal.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.