![]() |
VOOZH | about |
Given a binary string s consisting of only 0's and 1's, find the maximum difference between the number of 0s and the number of 1s (i.e., 0s − 1s) among all possible substrings of the string. If the string contains only 1s, then it is not possible to obtain a positive difference, so the result is -1.
Examples:
Input: s = "11000010001"
Output: 6
Explanation: From index 2 to index 9, there are 7 zeros and 1 one. So, number of 0s - number of 1s = 7 - 1 = 6.Input: s = "111111"
Output: -1
Explanation: The string contains only 1s, so no substring can give a positive difference.Input: s = "1001010"
Output: 3
Explanation: From index 1 to index 4, we have 3 zeros and 0 ones. So, difference = 3 - 0 = 3.
Table of Content
The idea is to check all possible substrings of the given binary string and compute the difference between the number of 0s and 1s. While traversing all substrings, we keep track of the maximum difference obtained so far. If no substring yields a positive difference, we return -1.
6
The idea is to convert the given binary string into an integer array by replacing 0 with +1 and 1 with -1. This transformation converts the problem into finding a subarray with the maximum sum, which directly represents the maximum difference (0s − 1s).
We traverse the array and consider every 0 as -1 and 1 as +1. We maintain a running sum (current_sum). If at any point the sum becomes negative, we reset it to 0, since a negative sum cannot contribute to a maximum. Along the traversal, we keep updating the maximum sum (max_sum) obtained so far.
If the final max_sum is 0, it means no valid substring exists (i.e., the string contains only 1s), so we return -1.
Consider the binary string: s = "11000010001"
Step 1: Convert the string and replace: 0 -> +1 and 1 -> -1. So the transformed array becomes: -1 -1 +1 +1 +1 +1 -1 +1 +1 +1 -1
Step 2: Initialize variables current_sum = 0 and max_sum = 0
Step 3: Traverse the array
Step 4: Maximum difference (0's - 1's) = 6
6