Given a binary string of 0s and 1s. The task is to find the length of substring which is having 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
The idea is to use Dynamic Programming to solve the problem.
Before that we will convert given binary string into integer array of value 1s and -1s, say arr. That can be easily done by traversing the given binary string and if ith index contain ‘0’ make -1 in corresponding position in array. Similarly, if ith index contain ‘1’, make 1 in the array.
Now, at each index i we need to make decision whether to take it or skip it. So, declare a 2D array of size n x 2, where n is the length of the given binary string, say dp[n].
dp[i] define the maximum value upto index i, when we skip the i-th index element. dp[i] define the maximum value upto index i after taking the i-th index element. Therefore, we can derive dp[i] as: dp[i] = max(dp[i+1], dp[i+1] + arr[i]) dp[i] = max(dp[i+1] + arr[i], 0)
For all ones we check this case explicitly.
- Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
- Maximum consecutive one’s (or zeros) in a binary array
- Maximum contiguous 1 possible in a binary string after k rotations
- Maximum Consecutive Zeroes in Concatenated Binary String
- Arrange a binary string to get maximum value within a range of indices
- Count binary strings with twice zeros in first half
- Maximum length of consecutive 1's in a binary string in Python using Map function
- Maximum number of trailing zeros in the product of the subsets of size k
- Maximum sum of pairs with specific difference
- Maximum absolute difference between sum of two contiguous sub-arrays
- Maximum length subsequence with difference between adjacent elements as either 0 or 1
- Python | Check if a given string is binary string or not
- Remove one bit from a binary number to get maximum value
- Maximum decimal value path in a binary matrix
- Check whether row or column swaps produce maximum size binary sub-matrix with all 1s
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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 : DrRoot_