Solution:
Because we split the string into two different continuous parts, we are able to develop an efficient O(n) algorithm.
Determine the number of characters '1' in the given string and store them in a variable.
Start traversing from the 0th to the n-2nd character.
At each step, if the current character is '0', we increase zero, or if it is '1', we decrease the count one variable. Finally, you can get the result by getting one plus zero
Return the result.
Code:
class Solution {
public:
int maxScore(string s) {
int res = 0, one = 0, zero = 0;
for(char ch : s) {
if(ch == '1')
++one;
}
const int n = (int) s.size();
for(int i = 0; i < n - 1; ++i) {
if(s[i] == '0')
++zero;
else
--one;
res = max(res, one + zero);
}
return res;
}
};
💡
We currently use two loops to get the answer, could you reduce it to one?