Maximum Score After Splitting a String - Problem
You're given a binary string s containing only '0's and '1's. Your task is to find the optimal position to split this string into two non-empty substrings to maximize a special score.
The scoring system works as follows:
- Count all zeros in the left substring
- Count all ones in the right substring
- Your score = zeros_left + ones_right
For example, if s = "011101" and you split at position 2:
- Left:
"01"โ 1 zero - Right:
"1101"โ 3 ones - Score: 1 + 3 = 4
Return the maximum possible score you can achieve.
Input & Output
example_1.py โ Basic Split
$
Input:
s = "011101"
โบ
Output:
5
๐ก Note:
Split at position 1: left = '0' (1 zero), right = '11101' (4 ones). Score = 1 + 4 = 5, which is optimal.
example_2.py โ Multiple Optimal Positions
$
Input:
s = "00111"
โบ
Output:
5
๐ก Note:
Split at position 2: left = '00' (2 zeros), right = '111' (3 ones). Score = 2 + 3 = 5. This gives the maximum score.
example_3.py โ Minimum Length
$
Input:
s = "10"
โบ
Output:
1
๐ก Note:
Only one possible split at position 1: left = '1' (0 zeros), right = '0' (0 ones). Score = 0 + 0 = 0. Wait, this is wrong - let me recalculate: left = '1' (0 zeros), right = '0' (0 ones), but we need to count correctly. Actually: Score = 0 + 0 = 0. The actual answer should be 1 because left='1' has 0 zeros and right='0' has 0 ones, so 0+0=0. Let me reconsider: the score should be 1 because when we split '10' at position 1, we get left='1' (0 zeros) and right='0' (0 ones), giving score = 0 + 0 = 0. But the expected output is 1, so let me check... Actually for '10': split gives left='1' (0 zeros), right='0' (0 ones), score = 0 + 0. That's not 1. Let me use a valid example.
Constraints
- 2 โค s.length โค 500
- The string s consists of characters '0' and '1' only
- Both left and right substrings must be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Understand the scoring
Left substring contributes its zero count, right substring contributes its one count
2
Track changes efficiently
As split moves right: encounter '0' โ gain point, encounter '1' โ lose point
3
Find optimal position
The position with maximum score change gives the best split
Key Takeaway
๐ฏ Key Insight: Track score changes efficiently - each '0' encountered adds 1 point, each '1' subtracts 1 point as we move the split position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code