{x}
blog image

Maximum Score After Splitting a String

Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

 

Example 1:

Input: s = "011101"
Output: 5 
Explanation: 
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5 
left = "01" and right = "1101", score = 1 + 3 = 4 
left = "011" and right = "101", score = 1 + 2 = 3 
left = "0111" and right = "01", score = 1 + 1 = 2 
left = "01110" and right = "1", score = 2 + 1 = 3

Example 2:

Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5

Example 3:

Input: s = "1111"
Output: 3

 

Constraints:

  • 2 <= s.length <= 500
  • The string s consists of characters '0' and '1' only.

Solution Explanation: Maximum Score After Splitting a String

This problem asks us to find the maximum score achievable by splitting a binary string into two non-empty substrings. The score is calculated as the sum of zeros in the left substring and ones in the right substring.

Approach: Efficient Counting

Instead of iterating through all possible splits, we can efficiently calculate the score by using a single pass through the string.

  1. Initialization:

    • r: Count the total number of 1s in the string. This represents the initial number of 1s in the right substring before any split.
    • l: Initialize to 0. This represents the initial number of 0s in the left substring (empty initially).
    • ans: Initialize to 0. This stores the maximum score found so far.
  2. Iteration:

    • Iterate through the string from left to right up to the second to last character (s[:-1] in Python).
    • For each character:
      • If the character is '0', increment l (adding a 0 to the left substring).
      • If the character is '1', decrement r (removing a 1 from the right substring).
    • After each character's processing, update ans to be the maximum of ans and the current l + r.
  3. Return: Return ans, which holds the maximum score.

Time Complexity: O(n), where n is the length of the string. We iterate through the string once.

Space Complexity: O(1). We only use a few variables to store the counts and the maximum score.

Code Implementation (Python)

class Solution:
    def maxScore(self, s: str) -> int:
        l, r = 0, s.count("1")  # Count of 1s initially in right substring
        ans = 0
        for x in s[:-1]:          #Iterate till second last character
            l += int(x) ^ 1       #Add 1 if 0, 0 if 1 (XOR trick)
            r -= int(x)           #Subtract 1 if 1, 0 if 0
            ans = max(ans, l + r)  #Update max score
        return ans

The Python code uses a bitwise XOR trick (int(x) ^ 1) to concisely check if the character is '0' (resulting in 1) or '1' (resulting in 0). This avoids using an if-else statement.

Code Implementation (Other Languages)

The logic remains the same across different languages, mainly differing in syntax:

Java:

class Solution {
    public int maxScore(String s) {
        int l = 0, r = 0;
        for (char c : s.toCharArray()) {
            if (c == '1') r++;
        }
        int ans = 0;
        for (int i = 0; i < s.length() - 1; ++i) {
            if (s.charAt(i) == '0') l++;
            else r--;
            ans = Math.max(ans, l + r);
        }
        return ans;
    }
}

C++:

class Solution {
public:
    int maxScore(string s) {
        int l = 0, r = 0;
        for (char c : s) {
            if (c == '1') r++;
        }
        int ans = 0;
        for (int i = 0; i < s.length() - 1; ++i) {
            if (s[i] == '0') l++;
            else r--;
            ans = max(ans, l + r);
        }
        return ans;
    }
};

Similar implementations can be done in other languages like C#, JavaScript, Go, etc., following the same algorithmic approach. The key is efficiently managing the counts of 0s in the left and 1s in the right substring during a single pass.