Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021

Given binary string str, the task is to maximize the count of 0s in the left substring and 1s in the right substring by splitting the given binary string at any index. Print the sum of such 0s and 1s in the end.

Examples: 

Input: str = “0011110011” 
Output:
Explanation: 
If a string is split at index 2, 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 3, 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.  

Approach:  

  1. Count the number of ones in the given binary string str (say totalOnes).
  2. Traverse the given string and keep the counts of 0s (say zero) and 1s (say one).
  3. During the string traversal, update the maximum sum as:

maxSum = max(maxSum, zero + (totalOnes – one))  



Below is the implementation of the above approach:  

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the sum of the count
// of zeros and ones in the left and right
// substring
int maxSum(string& str)
{
 
    int maximumSum = 0;
 
    // To store the total ones
    int totalOnes;
 
    // Count the total numbers of ones
    // in string str
    totalOnes = count(str.begin(),
                      str.end(), '1');
 
    // To store the count of zeros and
    // ones while traversing string
    int zero = 0, ones = 0;
 
    // Interate the given string and
    // update the maximum sum
    for (int i = 0; str[i]; i++) {
 
        if (str[i] == '0') {
            zero++;
        }
        else {
            ones++;
        }
 
        // Update the maximum Sum
        maximumSum
            = max(
                maximumSum,
                zero + (totalOnes - ones));
    }
 
    return maximumSum;
}
 
// Driver Code
int main()
{
    // Given binary string
    string str = "011101";
 
    // Function call
    cout << maxSum(str);
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG {
 
// Function to maximize the sum 
// of the count of zeros and ones 
// in the left and right substring
static int maxSum(String str)
{
    int maximumSum = 0;
 
    // To store the total ones
    int totalOnes = 0;
 
    // Count the total numbers of ones
    // in string str
    for(int i = 0; i < str.length(); i++)
    {
       if (str.charAt(i) == '1')
       {
           totalOnes++;
       }
    }
     
    // To store the count of zeros and
    // ones while traversing string
    int zero = 0, ones = 0;
 
    // Interate the given string and
    // update the maximum sum
    for(int i = 0; i < str.length(); i++)
    {
       if (str.charAt(i) == '0')
       {
           zero++;
       }
       else
       {
           ones++;
       }
        
       // Update the maximum Sum
       maximumSum = Math.max(maximumSum,
                            zero + (totalOnes - ones));
    }
     
    return maximumSum;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given binary string
    String str = "011101";
 
    // Function call
    System.out.println(maxSum(str));
}
}
 
// This code is contributed by rutvik_56

Python3




# Python3 program for the above approach
 
# Function to maximize the sum of the count
# of zeros and ones in the left and right
# substring
def maxSum(str):
 
    maximumSum = 0
 
    # To store the total ones
 
    # Count the total numbers of ones
    # in str
    totalOnes = 0
    for i in str:
        if i == '1':
            totalOnes += 1
 
    # To store the count of zeros and
    # ones while traversing string
    zero = 0
    ones = 0
 
    # Interate the given and
    # update the maximum sum
    i = 0
    while i < len(str):
 
        if (str[i] == '0'):
            zero += 1
        else:
            ones += 1
 
        # Update the maximum Sum
        maximumSum= max(maximumSum,zero + (totalOnes - ones))
        i += 1
 
    return maximumSum
 
# Driver Code
if __name__ == '__main__':
    # Given binary string
    str = "011101"
 
    # Function call
    print(maxSum(str))
 
# This code is contributed by mohit kumar 29

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to maximize the sum
// of the count of zeros and ones
// in the left and right substring
static int maxSum(string str)
{
    int maximumSum = 0;
 
    // To store the total ones
    int totalOnes = 0;
 
    // Count the total numbers of ones
    // in string str
    for(int i = 0; i < str.Length; i++)
    {
       if (str[i] == '1')
       {
           totalOnes++;
       }
    }
     
    // To store the count of zeros and
    // ones while traversing string
    int zero = 0, ones = 0;
 
    // Interate the given string and
    // update the maximum sum
    for(int i = 0; i < str.Length; i++)
    {
       if (str[i] == '0')
       {
           zero++;
       }
       else
       {
           ones++;
       }
        
       // Update the maximum Sum
       maximumSum = Math.Max(maximumSum, zero +
                                   (totalOnes -
                                    ones));
    }
    return maximumSum;
}
 
// Driver Code
public static void Main(string []args)
{
     
    // Given binary string
    string str = "011101";
 
    // Function call
    Console.Write(maxSum(str));
}
}
 
// This code is contributed by rutvik_56

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to maximize the sum of the count
// of zeros and ones in the left and right
// substring
function maxSum(str)
{
 
    var maximumSum = 0;
 
    // To store the total ones
    var totalOnes = 0;
 
    // Count the total numbers of ones
    // in string str
    str.split('').forEach(c => {
         
        if(c == '1')
            totalOnes++;
    });
 
    // To store the count of zeros and
    // ones while traversing string
    var zero = 0, ones = 0;
 
    // Interate the given string and
    // update the maximum sum
    for (var i = 0; str[i]; i++) {
 
        if (str[i] == '0') {
            zero++;
        }
        else {
            ones++;
        }
 
        // Update the maximum Sum
        maximumSum
            = Math.max(
                maximumSum,
                zero + (totalOnes - ones));
    }
 
    return maximumSum;
}
 
// Driver Code
// Given binary string
var str = "011101";
// Function call
document.write( maxSum(str));
 
 
</script>
Output: 
5

 

Time Complexity: O(N), where N is the length of the string.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :