Maximum Score After Splitting a String (LeetCode 1422): Solution and Explanation
Cut a binary string into two non-empty parts and score zeros on the left plus ones on the right. Return the best score over every cut.
Intuition
There are only n - 1 legal cuts, and adjacent cuts differ by a single character moving from the right part to the left part.
If that character is 0, the left part gains a zero. If it is 1, the right part loses a one. Either way the score changes by one, so it can be updated in O(1).
Start with every 1 counted on the right, then slide the cut and keep the best score seen.
Approach: Slide the cut with running counts
- Set ones to the number of 1s in s, and zeros = 0, best = 0.
- For i from 0 to n - 2, the cut moves to just after index i. If s[i] is '0', add one to zeros; otherwise subtract one from ones.
- Update best with zeros + ones.
- Return best.
Step-by-step example
s = "011101"
- ones = 4, zeros = 0.
- Cut after index 0 ('0'): zeros = 1, score 1 + 4 = 5, best = 5.
- Cuts after indices 1, 2, 3 each move a '1' left: ones drops to 3, 2, 1, scores 4, 3, 2.
- Cut after index 4 ('0'): zeros = 2, score 2 + 1 = 3.
- The cut cannot go after index 5, so the answer is 5.
Code: Python, Java, C++
1class Solution:
2 def maxScore(self, s: str) -> int:
3 ones = s.count('1')
4 zeros = 0
5 best = 0
6 for i in range(len(s) - 1):
7 if s[i] == '0':
8 zeros += 1
9 else:
10 ones -= 1
11 best = max(best, zeros + ones)
12 return best1class Solution {
2 public int maxScore(String s) {
3 int ones = 0;
4 for (char c : s.toCharArray()) {
5 if (c == '1') ones++;
6 }
7 int zeros = 0, best = 0;
8 for (int i = 0; i < s.length() - 1; i++) {
9 if (s.charAt(i) == '0') {
10 zeros++;
11 } else {
12 ones--;
13 }
14 best = Math.max(best, zeros + ones);
15 }
16 return best;
17 }
18}1class Solution {
2public:
3 int maxScore(string s) {
4 int ones = count(s.begin(), s.end(), '1');
5 int zeros = 0, best = 0;
6 for (int i = 0; i + 1 < (int)s.size(); i++) {
7 if (s[i] == '0') {
8 zeros++;
9 } else {
10 ones--;
11 }
12 best = max(best, zeros + ones);
13 }
14 return best;
15 }
16};Time and space complexity
O(n)
One pass to count the 1s and one pass over the n - 1 cuts.
O(1)
Three integer counters.
Other approaches
Brute force every cut (time O(n^2), space O(1))
For each cut, count zeros in the left part and ones in the right part from scratch. Fine for n up to 500 but quadratic.
One pass with a balance (time O(n), space O(1))
Score = zeros_left + (totalOnes - ones_left). Track zeros_left - ones_left over cuts in one pass, then add totalOnes at the end, so the string is read only once.
Common mistakes
- Allowing a cut after the last character. The right part must be non-empty, so the loop stops at n - 2.
- Allowing a cut before the first character, which leaves the left part empty. For "1111" that wrongly returns 4 instead of 3.
- Initialising best to the score of an empty split instead of evaluating only legal cuts.
Frequently asked questions
Why does the score change by exactly one per step?
Only one character changes sides. A 0 moving left adds a zero to the left count; a 1 moving left removes a one from the right count.
Can the answer be 0?
Yes. For "10" the only cut leaves "1" on the left and "0" on the right, which scores 0.
Is this a prefix sum problem?
It is the same idea. zeros is a running prefix count, and ones is the total minus a running prefix count of 1s.