Given a binary string of 0s and 1s. The task is to find the length of substring which is having a maximum difference of number of 0s and number of 1s (number of 0s – number of 1s). In case of all 1s print -1.
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)
- Minimum removals from array to make max - min <= K
- Maximize the sum of selected numbers from an array to make it empty
- Probability of reaching a point with 2 or 3 steps at a time
- Count of different ways to express N as the sum of 1, 3 and 4
- Maximum subarray sum in an array created after repeated concatenation
- Maximum value with the choice of either dividing or considering as it is
- Maximum difference of zeros and ones in binary string
- Maximum sum in a 2 x n grid such that no two elements are adjacent
- Maximum path sum for each position with jumps under divisibility condition
- Minimum cost to fill given weight in a bag
- Longest Zig-Zag Subsequence
- 0-1 Knapsack Problem | DP-10
- Minimum number of jumps to reach end
- Min Cost Path | DP-6
- Largest Sum Contiguous Subarray
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.
Improved By : jit_t