Program to find maximum score by splitting binary strings into two parts in Python

Suppose we have a binary string s. We need to split it into two non-empty substrings s1 and s2. The score of this split is the count of "0"s in s1 plus the count of "1"s in s2. We have to find the maximum score we can obtain.

So, if the input is like s = "011001100111", then the output will be 8, because we can split the string like "01100" + "1100111". Then, the score is 3 + 5 = 8.

Algorithm

To solve this, we will follow these steps ?

  • ones := number of "1"s in s

  • zeros := 0

  • ans := 0

  • for i in range 0 to size of s - 2, do

    • if s[i] is same as "0", then

      • zeros := zeros + 1

    • otherwise,

      • ones := ones - 1

    • ans := maximum of ans and (ones + zeros)

  • return ans

Example

Let us see the following implementation to get better understanding ?

def solve(s):
    ones = s.count("1")
    zeros = 0
    ans = 0
    for i in range(len(s) - 1):
        if s[i] == "0":
            zeros += 1
        else:
            ones -= 1
        ans = max(ans, ones + zeros)
    return ans

s = "011001100111"
print(solve(s))

The output of the above code is ?

8

How It Works

The algorithm works by iterating through all possible split positions. For each position, we track the count of zeros in the left part and ones in the right part. We maintain a running count to avoid recounting characters for each split position.

Binary String Split Example: "011001100111" String: 0 1 1 0 0 1 1 0 0 1 1 1 Optimal Split: "01100" 3 zeros "1100111" 5 ones Score = Zeros in left + Ones in right Score = 3 + 5 = 8 Legend: Zero (0) One (1)

Conclusion

This algorithm efficiently finds the maximum score by tracking zeros in the left part and ones in the right part for each possible split. The time complexity is O(n) where n is the length of the string.

Updated on: 2026-03-26T15:19:46+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements