Open In App

Maximize count of 0s in left and 1s in right substring by splitting given Binary string

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given a binary string str, the task is to split the given binary string at any index into two non-empty substrings such that the sum of counts of 0s in the left substring and 1s in the right substring is maximum. Print the sum of such 0s and 1s in the end.

Examples: 

Input: str = “0011110011” 
Output:
Explanation: 
If a string is split at index 1, then Left substring = “00” and Right substring = “11110011”. 
Therefore, the sum of the count of 0s in left substring and 1s in right substring is 2 + 6 = 8.

Input: str = “0001101111011” 
Output: 11 
Explanation: 
If the string is split at index 2, then the Left substring is “000” and the right substring is “1101111011”. 
Therefore, the sum of the count of 0s in left substring and 1s in right substring is 3 + 8 = 11.  

[Naive Approach] – Consider Every Cut and Count – O(n2) Time and O(1) Space

The idea is to consider every cut and count 0s on left and 1st on right. At the end return the maximum count.

[Expected Approach] – Count All Ones – O(n) Time and O(1) Space

The idea is to find the optimal split point that maximizes the sum of zeros in the left substring and ones in the right substring.

We first count total ones in the string, then iterate through each possible split point (except the last character to ensure right substring isn’t empty).

At each point, we maintain counts of zeros and ones seen so far in the left part. The maximum sum at any split point will be (zeros in left) + (total ones – ones in left), where (total ones – ones in left) gives us the ones in right substring. We track the maximum such sum found across all split points.

Below is the implementation of the above approach:  

C++
Java Python C# JavaScript

Output
5


Next Article

Similar Reads