Problem Description
Given a string s consisting of characters '0' and '1', the task is to split the string into two non-empty substrings (a left and a right) such that the score is maximized. The score is defined as the number of zeros in the left substring plus the number of ones in the right substring.
Key Insights
- The split can occur at any index from 1 to n-1 (where n is the length of the string) to ensure both substrings are non-empty.
- Pre-calculate the total number of ones in the original string.
- As you iterate through possible splits, maintain a running count of zeros seen so far (for the left substring) and ones seen so far. The ones in the right substring can be computed as (total ones - ones in the left substring).
- The maximum score is obtained by iteratively checking the score at each split position.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because we scan the string once. Space Complexity: O(1), as only a few counters are used.
Solution
We approach the problem using a single pass. First, count the total number of ones in the string. Then, iterate through the string (except for the last character to ensure the right substring is non-empty) and maintain two counters: one for zeros (left score contribution) and one for ones (to subtract from total ones for the right substring). At each index, the score is computed as (zeros_count + (totalOnes - ones_count)). We update the maximum score seen. This efficient use of prefix sum ideas allows us to compute the answer in O(n) time using constant extra space.