class Solution:
def maxScore(self, s: str) -> int:
max_score = 0
left_zeros = 0
right_ones = s.count('1')
# We cannot split at the last character
for i in range(len(s)-1):
if s[i] == '0':
left_zeros += 1
else:
right_ones -= 1
max_score = max(max_score, left_zeros + right_ones)
return max_score
class Solution {
public:
int maxScore(string s) {
int max_score = 0;
int left_zeros = 0;
int right_ones = count(s.begin(), s.end(), '1');
// Cannot split at the last character
for (int i = 0; i < s.size() - 1; ++i) {
if (s[i] == '0') left_zeros++;
else right_ones--;
max_score = max(max_score, left_zeros + right_ones);
}
return max_score;
}
};
class Solution {
public int maxScore(String s) {
int maxScore = 0;
int leftZeros = 0;
int rightOnes = 0;
for (char c : s.toCharArray()) {
if (c == '1') rightOnes++;
}
// Cannot split at the last character
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == '0') leftZeros++;
else rightOnes--;
maxScore = Math.max(maxScore, leftZeros + rightOnes);
}
return maxScore;
}
}
var maxScore = function(s) {
let maxScore = 0;
let leftZeros = 0;
let rightOnes = 0;
for (let c of s) {
if (c === '1') rightOnes++;
}
// Cannot split at the last character
for (let i = 0; i < s.length - 1; i++) {
if (s[i] === '0') leftZeros++;
else rightOnes--;
maxScore = Math.max(maxScore, leftZeros + rightOnes);
}
return maxScore;
};
s
(a string only containing '0' and '1'), you want to split it into two non-empty substrings at some index. The score for a split is the number of '0's in the left substring plus the number of '1's in the right substring. Your task is to return the maximum possible score you can get from any valid split. Note that you cannot split at the last character (both substrings must be non-empty).
s
. This will be our initial count of ones on the right side.left_zeros
) and set it to 0.left_zeros
(since this zero will be on the left after the split).right_ones
(since this one will move from right to left after the split).left_zeros + right_ones
and update the maximum score found so far.s = "011101"
as an example.
n-1
split points, count zeros and ones in both substrings, which is O(n) per split, so O(n^2) time.