You are given a binary string. You are supposed to find the maximum difference between the number of zeros(0's) and the number of ones(1's) in any substring of the given string.
Note:Binary String is a string that consists of only ‘0’s and ‘1’s.
A string ‘A’ is said to be a substring of string ‘B’ if ‘A’ can be obtained by deleting several characters(possibly none) from the start of ‘B’ and by deleting several characters(possibly none) from the end of ‘B’.
The substring must have a length greater than or equal to 1.
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains a binary string.
Output Format:
Print the maximum difference between the number of zeros and the number of ones in any substring of the given string.
Print the output of each test case in a new line.
1<= T <= 100
1 <= |S| <= 10,000
S[i] = ‘0’ / ‘1’
Time Limit: 1 sec
2
1100010001
1101
5
1
In the first test case, the binary string is ‘1100010001’. To find out the maximum difference between the number of zeros and the number of ones in the substring of the string, We have a substring from index 2 to 8, which consists of all ‘0’s except the 5th index, which is ‘1’. So, the answer is 6 - 1 = 5.
In the second test case, the binary string is ‘1101’. To find out the maximum difference between the number of zeros and the number of ones in the substring of the string, We have a substring from index 2 to 2(length = 1), which consists of one ‘0’s and zero ‘1’s, So, the answer is 1 - 0 = 0.
2
000000
0101010101
6
1
Make all the possible substrings and then count the maximum difference between the number of zeros and the number of ones in the substring of the string.
The idea is to check all the possible substrings and count the difference between the number of zeros and the number of ones in every substring.
O(|S| ^ 3), where |S| is the length of the given string.
As we are iterating having two loops for fixing the leftmost and the rightmost index of the substring and one more for counting the answer of the current substring. Hence, the overall time complexity is O(|S| ^ 3).
O(1)
As we are using constant space.