Given a binary string of 0s and 1s. The task is to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string. That is maximize ( number of 0s – number of 1s ) for any sub-string in the given binary string.
Examples:
Input : S = "11000010001" Output : 6 From index 2 to index 9, there are 7 0s and 1 1s, so number of 0s - number of 1s is 6. Input : S = "1111" Output : -1
We have discussed Dynamic Programming approach in below post :
Maximum difference of zeros and ones in binary string | Set 1. 
In the post we seen an efficient method that work in O(n) time and in O(1) extra space. Idea behind that if we convert all zeros into 1 and all ones into -1.now our problem reduces to find out the maximum sum sub_array Using Kadane’s Algorithm. 
Input : S = "11000010001"
     After converting '0' into 1 and
     '1' into -1 our S Look Like
      S  = -1 -1 1 1 1 1 -1 1 1 1 -1
 Now we have to find out Maximum Sum sub_array 
 that is  : 6 is that case 
    
Output : 6
Below is the implementation of above idea.
C++
| // CPP Program to find the length of// substring with maximum difference of// zeros and ones in binary string.#include <iostream>usingnamespacestd;// Returns the length of substring with// maximum difference of zeroes and ones // in binary stringintfindLength(string str, intn){    intcurrent_sum = 0;    intmax_sum = 0;    // traverse a binary string from left     // to right    for(inti = 0; i < n; i++) {        // add current value to the current_sum        // according to the Character        // if it's '0' add 1 else -1        current_sum += (str[i] == '0'? 1 : -1);        if(current_sum < 0)            current_sum = 0;        // update maximum sum        max_sum = max(current_sum, max_sum);    }    // return -1 if string does not contain    // any zero that means all ones     // otherwise max_sum    returnmax_sum == 0 ? -1 : max_sum;}// Driven Programintmain(){    string s = "11000010001";    intn = 11;    cout << findLength(s, n) << endl;    return0;} | 
Java
| // Java Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.importjava.util.*;importjava.lang.*;importjava.io.*;classGFG {    // Find the length of substring with maximum    // difference of zeros and ones in binary    // string    publicstaticintfindLength(String str, intn)    {        intcurrent_sum = 0;        intmax_sum = 0;        // traverse a binary string from left to right        for(inti = 0; i < n; i++) {            // add current value to the current_sum            // according to the Character            // if it's '0' add 1 else -1            current_sum += (str.charAt(i) == '0'? 1: -1);            if(current_sum < 0)                current_sum = 0;            // update maximum sum            max_sum = Math.max(current_sum, max_sum);        }        // return -1 if string does not contain any zero        // that means string contains all ones otherwise max_sum        returnmax_sum == 0? -1: max_sum;    }    publicstaticvoidmain(String[] args)    {        String str = "11000010001";        intn = str.length();        System.out.println(findLength(str, n));    }} | 
Python3
| # Python Program to find the length of# substring with maximum difference of# zeros and ones in binary string.# Returns the length of substring with# maximum difference of zeroes and ones # in binary stringdeffindLength(string, n):    current_sum =0    max_sum =0    # traverse a binary string from left     # to right    fori inrange(n):        # add current value to the current_sum        # according to the Character        # if it's '0' add 1 else -1        current_sum +=(1ifstring[i] =='0'else-1)        ifcurrent_sum < 0:            current_sum =0        # update maximum sum        max_sum =max(current_sum, max_sum)    # return -1 if string does not contain    # any zero that means all ones     # otherwise max_sum    returnmax_sum ifmax_sum else0# Driven Programs ="11000010001"n =11print(findLength(s, n))# This code is contributed by Ansu Kumari. | 
C#
| // C# Program to find the length of // substring with maximum difference of // zeroes and ones in binary string. usingSystem;classGFG{// Find the length of substring with // maximum difference of zeros and // ones in binary string publicstaticintfindLength(stringstr,                              intn){    intcurrent_sum = 0;    intmax_sum = 0;    // traverse a binary string     // from left to right     for(inti = 0; i < n; i++)    {        // add current value to the current_sum         // according to the Character         // if it's '0' add 1 else -1         current_sum += (str[i] == '0'? 1 : -1);        if(current_sum < 0)        {            current_sum = 0;        }        // update maximum sum         max_sum = Math.Max(current_sum, max_sum);    }    // return -1 if string does not contain     // any zero that means string contains     // all ones otherwise max_sum     returnmax_sum == 0 ? -1 : max_sum;}// Driver CodepublicstaticvoidMain(string[] args){    stringstr = "11000010001";    intn = str.Length;    Console.WriteLine(findLength(str, n));}}// This code is contributed by Shrikant13 | 
PHP
| <?php// PHP Program to find the length of// substring with maximum difference of// zeros and ones in binary string.// Returns the length of substring with// maximum difference of zeroes and ones // in binary stringfunctionfindLength($str, $n){    $current_sum= 0;    $max_sum= 0;    // traverse a binary string    // from left to right    for($i= 0; $i< $n; $i++)     {        // add current value to the current_sum        // according to the Character        // if it's '0' add 1 else -1        $current_sum+= ($str[$i] == '0'? 1 : -1);        if($current_sum< 0)            $current_sum= 0;        // update maximum sum        $max_sum= max($current_sum, $max_sum);    }    // return -1 if string does not contain    // any zero that means all ones     // otherwise max_sum    return$max_sum== 0 ? -1 : $max_sum;}    // Driver Code    $s= "11000010001";    $n= 11;    echofindLength($s, $n),"\n";    // This code is contributed by aj_36?> | 
Javascript
| <script>// JavaScript program to find the length of // substring with maximum difference of // zeroes and ones in binary string. // Find the length of substring with // maximum difference of zeros and // ones in binary string functionfindLength(str, n){      let current_sum = 0;    let max_sum = 0;      // traverse a binary string     // from left to right     for(let i = 0; i < n; i++)    {          // add current value to the current_sum         // according to the Character         // if it's '0' add 1 else -1         current_sum += (str[i] == '0' ? 1 : -1);          if(current_sum < 0)        {            current_sum = 0;        }          // update maximum sum         max_sum = Math.max(current_sum, max_sum);    }    // return -1 if string does not contain     // any zero that means string contains     // all ones otherwise max_sum     returnmax_sum == 0 ? -1 : max_sum;}// Driver Code    let str = "11000010001";    let n = str.length;      document.write(findLength(str, n));            // This code is contributed by chinmoy1997pal.</script> | 
6
Time Complexity: O(n) 
Space complexity: O(n), since string gets copied when we pass it to a function.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







