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.
Input: s ="011101"Output: 5Explanation:
All possible ways of splitting s into two non-empty substrings are:left ="0" and right ="11101", score =1+4=5left ="01" and right ="1101", score =1+3=4left ="011" and right ="101", score =1+2=3left ="0111" and right ="01", score =1+1=2left ="01110" and right ="1", score =2+1=3
The key idea is to try every possible split between the left and right substrings, count zeros on the left and ones on the right, and keep track of the maximum score. We can efficiently do this by precomputing the total number of ones and then iterating through the string, updating counts as we go.
classSolution {
public:int maxScore(string s) {
int ones =0, ans =0, zeros =0;
for (char c : s) if (c =='1') ones++;
int n = s.size();
for (int i =0; i < n -1; ++i) {
if (s[i] =='0') zeros++;
else ones--;
ans = max(ans, zeros + ones);
}
return ans;
}
};
classSolution {
publicintmaxScore(String s) {
int ones = 0, zeros = 0, ans = 0;
for (char c : s.toCharArray()) if (c =='1') ones++;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) =='0') zeros++;
else ones--;
ans = Math.max(ans, zeros + ones);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxScore(s: String): Int {
var ones = s.count { it=='1' }
var zeros = 0var ans = 0for (i in0 until s.length - 1) {
if (s[i] =='0') zeros++else ones-- ans = maxOf(ans, zeros + ones)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defmaxScore(self, s: str) -> int:
ones: int = s.count('1')
zeros: int =0 ans: int =0for i in range(len(s) -1):
if s[i] =='0':
zeros +=1else:
ones -=1 ans = max(ans, zeros + ones)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_score(s: String) -> i32 {
let bytes = s.as_bytes();
letmut ones = bytes.iter().filter(|&&c| c ==b'1').count() asi32;
letmut zeros =0;
letmut ans =0;
for i in0..bytes.len() -1 {
if bytes[i] ==b'0' {
zeros +=1;
} else {
ones -=1;
}
ans = ans.max(zeros + ones);
}
ans
}
}