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.
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 Programing 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.
Time Complexity : O(n)
Space complexity : O(1)
- Maximum difference of zeros and ones in binary string
- Maximum consecutive one’s (or zeros) in a binary array
- Maximum consecutive one’s (or zeros) in a binary circular array
- Find the maximum possible Binary Number from given string
- Maximum contiguous 1 possible in a binary string after k rotations
- Arrange a binary string to get maximum value within a range of indices
- Maximum Consecutive Zeroes in Concatenated Binary String
- Maximum length of consecutive 1's in a binary string in Python using Map function
- Count binary strings with twice zeros in first half
- Maximum number of trailing zeros in the product of the subsets of size k
- Longest sub string of 0's in a binary string which is repeated K times
- Time complexity of all permutations of a string
- Python | Check if a given string is binary string or not
- Maximum sum of pairs with specific difference
- Find time taken for signal to reach all positions in a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.