Maximum difference of zeros and ones in binary string
Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the 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
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.
Time Complexity: O(2*len(s)),
Auxiliary Space: O(len(s))