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
[Naive Approach] Check All Substrings - O(n^2) Time and O(1) Space
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.
using namespace std;
// Function to find the maximum difference (0s - 1s)
int maxSubstring(string &s) {
int n = s.length();
int maxDiff = INT_MIN;
// Iterate over all possible substrings
for (int i = 0; i < n; i++) {
int count0 = 0, count1 = 0;
// Check each substring starting at index i
for (int j = i; j < n; j++) {
if (s[j] == '0')
count0++;
else
count1++;
int diff = count0 - count1;
maxDiff = max(maxDiff, diff);
}
}
// If no valid substring (all 1s), return -1
return (maxDiff <= 0) ? -1 : maxDiff;
}
int main() {
string s = "11000010001";
cout << maxSubstring(s);
return 0;
}
public class GFG {
// Function to find the maximum difference (0s - 1s)
public static int maxSubstring(String s) {
int n = s.length();
int maxDiff = Integer.MIN_VALUE;
// Iterate over all possible substrings
for (int i = 0; i < n; i++) {
int count0 = 0, count1 = 0;
// Check each substring starting at index i
for (int j = i; j < n; j++) {
if (s.charAt(j) == '0')
count0++;
else
count1++;
int diff = count0 - count1;
maxDiff = Math.max(maxDiff, diff);
}
}
// If no valid substring (all 1s), return -1
return (maxDiff <= 0) ? -1 : maxDiff;
}
public static void main(String[] args) {
String s = "11000010001";
System.out.println(maxSubstring(s));
}
}
import sys
# Function to find the maximum difference (0s - 1s)
def maxSubstring(s):
n = len(s)
maxDiff = -sys.maxsize
# Iterate over all possible substrings
for i in range(n):
count0 = 0
count1 = 0
# Check each substring starting at index i
for j in range(i, n):
if s[j] == '0':
count0 += 1
else:
count1 += 1
diff = count0 - count1
maxDiff = max(maxDiff, diff)
# If no valid substring (all 1s), return -1
return -1 if maxDiff <= 0 else maxDiff
if __name__ == "__main__":
s = "11000010001"
print(maxSubstring(s))
using System;
class GFG
{
// Function to find the maximum difference (0s - 1s)
static int maxSubstring(string s)
{
int n = s.Length;
int maxDiff = int.MinValue;
// Iterate over all possible substrings
for (int i = 0; i < n; i++)
{
int count0 = 0, count1 = 0;
// Check each substring starting at index i
for (int j = i; j < n; j++)
{
if (s[j] == '0')
count0++;
else
count1++;
int diff = count0 - count1;
maxDiff = Math.Max(maxDiff, diff);
}
}
// If no valid substring (all 1s), return -1
return (maxDiff <= 0) ? -1 : maxDiff;
}
static void Main(string[] args)
{
string s = "11000010001";
Console.WriteLine(maxSubstring(s));
}
}
// Function to find the maximum difference (0s - 1s)
function maxSubstring(s) {
let n = s.length;
let maxDiff = Number.MIN_SAFE_INTEGER;
// Iterate over all possible substrings
for (let i = 0; i < n; i++) {
let count0 = 0, count1 = 0;
// Check each substring starting at index i
for (let j = i; j < n; j++) {
if (s[j] === '0')
count0++;
else
count1++;
let diff = count0 - count1;
maxDiff = Math.max(maxDiff, diff);
}
}
// If no valid substring (all 1s), return -1
return (maxDiff <= 0) ? -1 : maxDiff;
}
let s = "11000010001";
console.log(maxSubstring(s));
Output
6
[Efficient Approach] Kadane’s Algorithm - O(n) Time and O(1) Space
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
- -1 -> current_sum = -1 -> reset to 0, max_sum = 0
- -1 -> current_sum = -1 -> reset to 0, max_sum = 0
- +1 -> current_sum = 1 -> max_sum = 1
- +1 -> current_sum = 2 -> max_sum = 2
- +1 -> current_sum = 3 -> max_sum = 3
- +1 -> current_sum = 4 -> max_sum = 4
- -1 -> current_sum = 3 -> max_sum = 4
- +1 -> current_sum = 4 -> max_sum = 4
- +1 -> current_sum = 5 -> max_sum = 5
- +1 -> current_sum = 6 -> max_sum = 6
- -1 -> current_sum = 5 -> max_sum = 6
Step 4: Maximum difference (0's - 1's) = 6
#include <iostream>
using namespace std;
int maxSubstring(string str)
{ int n = str.length();
int current_sum = 0;
int max_sum = 0;
// traverse a binary string from left
// to right
for (int i = 0; i < n; i++) {
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str[i] == '0' ? 1 : -1);
if (current_sum < 0)
current_sum = 0;
// update maximum sum
max_sum = max(current_sum, max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return max_sum == 0 ? -1 : max_sum;
}
int main()
{
string s = "11000010001";
cout << maxSubstring(s) << endl;
return 0;
}
class GFG {
static int maxSubstring(String str)
{
int n = str.length();
int current_sum = 0;
int max_sum = 0;
// traverse a binary string from left
// to right
for (int i = 0; i < n; i++) {
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str.charAt(i) == '0' ? 1 : -1);
if (current_sum < 0)
current_sum = 0;
// update maximum sum
max_sum = Math.max(current_sum, max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return (max_sum == 0) ? -1 : max_sum;
}
public static void main(String[] args)
{
String s = "11000010001";
System.out.println(maxSubstring(s));
}
}
# Function to find the maximum difference (0s - 1s)
def maxSubstring(str):
n = len(str)
current_sum = 0
max_sum = 0
# traverse a binary string from left
# to right
for i in range(n):
# add current value to the current_sum
# according to the Character
# if it's '0' add 1 else -1
current_sum += (1 if str[i] == '0' else -1)
if current_sum < 0:
current_sum = 0
# update maximum sum
max_sum = max(current_sum, max_sum)
# return -1 if string does not contain
# any zero that means all ones
# otherwise max_sum
return -1 if max_sum == 0 else max_sum
if __name__ == "__main__":
s = "11000010001"
print(maxSubstring(s))
using System;
class GFG
{
static int maxSubstring(string str)
{
int n = str.Length;
int current_sum = 0;
int max_sum = 0;
// traverse a binary string from left
// to right
for (int i = 0; i < n; i++)
{
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str[i] == '0' ? 1 : -1);
if (current_sum < 0)
current_sum = 0;
// update maximum sum
max_sum = Math.Max(current_sum, max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return (max_sum == 0) ? -1 : max_sum;
}
static void Main(string[] args)
{
string s = "11000010001";
Console.WriteLine(maxSubstring(s));
}
}
function maxSubstring(str)
{
let n = str.length;
let current_sum = 0;
let max_sum = 0;
// traverse a binary string from left
// to right
for (let i = 0; i < n; i++) {
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str[i] === '0' ? 1 : -1);
if (current_sum < 0)
current_sum = 0;
// update maximum sum
max_sum = Math.max(current_sum, max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return (max_sum === 0) ? -1 : max_sum;
}
let s = "11000010001";
console.log(maxSubstring(s));
Output
6