Leetcode 1422. Maximum Score After Splitting a String
You are given a string s
of zeros and ones. You can split the string into two non-empty substrings left
and right
where left
is a substring of s
from the start of the string to an index i
(0 <= i < s.length - 1) and right
is a substring of s
from index i + 1
to the end of the string. The score after splitting the string is the number of zeros in left
plus the number of ones in right
. Return the maximum score you can achieve after splitting the string s.
Q: What is the length range of the input string s
?
A: The length of the input string s
will be between 2
and 500
.
Q: Can the input string s
be composed of characters other than 0
and 1
?
A: No, the input string s
will only contain the characters 0
and 1
.
Q: Given that the split must be non-empty, is there a specific rule for how the minimum length of both substrings should be?
A: Both substrings must be non-empty, meaning left
will consist of at least one character from the start, and right
will consist of at least one character from the end.
Initial Count Setup: Start by counting the total number of ones in the string, which will help in calculating the score of the right part dynamically.
countOnesInRight
as we shift the split point to the right.Score Calculation: At each split point, calculate the score by adding the number of zeros in the left part to the number of ones in the right part.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int maxScore(string s) {
int countOnesInRight = count(s.begin(), s.end(), '1');
int countZerosInLeft = 0;
int maxScore = 0;
for (int i = 0; i < s.size() - 1; ++i) {
if (s[i] == '0') {
++countZerosInLeft;
} else {
--countOnesInRight;
}
maxScore = max(maxScore, countZerosInLeft + countOnesInRight);
}
return maxScore;
}
// Example usage:
int main() {
string s = "011101";
cout << "Maximum score after splitting the string: " << maxScore(s) << endl;
return 0;
}
This approach ensures that we are handling each character in the string efficiently and calculating the maximum possible score by evaluating every potential split point exactly once.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?