[LeetCode] Maximum Score After Splitting a String

1422. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxScore(string s) {
int z = 0, o = count(begin(s),end(s),'1');
int res = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(s[i] == '1') o -= 1;
else z += 1;
res = max(res, o + z);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/22/PS/LeetCode/maximum-score-after-splitting-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.