解题思路:
首先遍历一遍数组将1和0的个数统计下来,接着重新遍历数组,记录当前左0个数和右1个数,注意,右1个数可以通过1总个数减去左1个数得到,得分即左0+右1,更新最大值,代码如下:
class Solution {
public:
int maxScore(string s) {
int n = s.size();
int count0 = 0, count1 = 0;
for(int i = 0; i < n; i ++) {
count0 += (s[i] == '0' ? 1 : 0);
}
count1 = n - count0;
int score = 0;
int left0 = 0, right1 = 0;
for(int i = 0; i < n - 1; i ++) {
if(s[i] == '0') {
left0 ++;
}
right1 = count1 - (i + 1 - left0);
score = max(score, left0 + right1);
}
return score;
}
};