Maximum difference of zeros and ones in binary string | Practice | GeeksforGeeks

Given a binary string S consisting of 0s and 1s. The task is to find the maximum difference of the number of 0s and the number of 1s (number of 0s – number of 1s) in the substrings of a string.
Note: In the case of all 1s, the answer will be -1. 
Example 1:
Input : S = "11000010001" 
Output : 6 
Explanatio: From index 2 to index 9, 
there are 7 0s and 1 1s, so number 
of 0s - number of 1s is 6. 
Example 2:
Input: S = "111111"
Output: -1
Explanation: S contains 1s only 
Your task:
You do not need to read any input or print anything. The task is to complete the function maxSubstring(), which takes a string as input and returns an integer. 
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105
S contains 0s and 1s only
+1
sanketbhagat2 days ago
SIMPLE JAVA SOLUTION
class Solution {
    int zero=0,one=0,ans=-1;
    int maxSubstring(String s) {
        // code here
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='0') zero++;
            else one++;
            if(zero>one) ans = Math.max(ans,zero-one);
            else zero = one = 0;
        }
        return ans;
    }
}
0
milindprajapatmst191 week ago
class Solution {
public:	
	int maxSubstring(string& str) {
	    int one = 0, zero = 0, result = -1;
	    for (char& ch : str) {
	        one += (ch == '1');
	        zero += (ch == '0');
	        result = max(result, zero - one);
	        if (zero - one < 0)
	            one = zero = 0;
	    }
	    return result;
	}
};
0
jainmuskan5652 weeks ago
 int maxSubstring(string S){    // create vector for the amount the binary string adds 0/1    vector<int> arr(S.size(),0);    for(int i=0;i<S.size();i++){        if(S[i]=='1'){            arr[i]=-1;        }        else{            arr[i]=1;        }    }    // kadanes maxSum    int sum=0,maxSum=INT_MIN;    for(int i=0;i<arr.size();i++){        sum+= arr[i];        maxSum=max(maxSum,sum);        if(sum<0){            sum=0;        }    }    return maxSum;}
+1
dattatraygujar773 weeks ago
 //O(1) SPACE
 int maxSubstring(String S) {
       int i=0,max=-1,count=0,count1=0;
       while(i<S.length())
       {
           if(S.charAt(i)=='0')
           {
               count++;
               max=Math.max(max,count-count1); 
           }
           if(count>0 && S.charAt(i)=='1')
           {
              count1++;
              max=Math.max(max,count-count1+1);
              if(count-count1 < 0)
              {
              count1=0;
              count=0;
              }
           }
          
          i++;
       }
       return max;
    }
0
sandeepkmrnayak4 weeks ago
This Problem is same as Maximum Subarray Sum
int maxSubstring(string S)
	{
	    // Your code goes here
	    int ans = 0;
	    int temp = 0;
	    for(int i=0;i<S.size();i++)
	    {
	        if(S[i]=='0')
	        {
	            temp++;
	        }
	        else
	        {
	            temp--;
	        }
	        ans = max(ans,temp);
	        if(temp<0)
	        {
	            temp = 0;
	        }
	    }
	    return ans==0?-1:ans;
	}
+1
madhukartemba1 month ago
JAVA SOLUTION O(1) SPACE COMPLEXITY:
THIS PROBLEM CAN BE SOLVED BY MODIFYING KADANE'S ALGORITHM:
 
class Solution {
    int maxSubstring(String S) {
        int n = S.length();
        int i = 0;
        while(i<n && S.charAt(i)=='1')
        {
            i++;
        }
        
        if(i==n) return -1;
        
        int max_diff = 0, diff = 0;
        while(i<n)
        {
            if(S.charAt(i++)=='0')
            {
                diff++;
            }
            else
            {
                max_diff = Math.max(diff, max_diff);
                diff--;
            }
            
            if(diff<0) diff=0;
            
            max_diff = Math.max(diff, max_diff);
        }
        
        return max_diff;
    }
}
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.0 / 1.6 sec
 
int maxSubstring(string S){    int max_so_far = 0;    int curr_max = 0;    for(int i = 0; i < S.length(); i++){        int x = S[i] == '0' ? 1 : -1;        curr_max += x;        max_so_far = max(max_so_far,curr_max);        if(curr_max < 0) curr_max = 0;    }    return (max_so_far == 0 ? -1 : max_so_far);}
0
anuragncp2 months ago
Cakewalk C++ solution 
‘’'int maxSubstring(string S){    // Your code goes here    int n = S.length() ;    int dp[n+1] ;    dp[0] = 0 ;    int m = -1 ;    for(int i=1;i<=n;i++)    {        if(S[i-1]=='1') dp[i] = max(dp[i-1]-1,-1) ;        else dp[i] = 1+max(0,dp[i-1]) ;        m = max(m,dp[i]) ;    }  return m ;  } ‘’'
0
rakeshkumarverma20223 months ago
c++ solution time(O(n)), space(O(1))
 int maxSubstring(string S){   int dif=0,ans=0;   for(int i=0;i<S.length();i++){       if(S[i]=='1')           dif=--dif<0?0:dif;       else           ans=max(ans,++dif);   }   return ans==0?-1:ans;   }
0
himanshukug19cs3 months ago
java solution
 
 int maxSubstring(String S) {       // code here   int ans=0;   int[] dp = new int[S.length()];   int sum=0;   if(S.charAt(0)=='1')      dp[0]=0;   else{      dp[0]=1;      ans=1;   }   for(int i=1;i<S.length();i++){   if(S.charAt(i)=='1'){       if(dp[i-1]==0)          dp[i]=0;       else              dp[i]=Math.max(dp[i-1]-1,-1);         }   else      dp[i]=dp[i-1]+1;   ans=Math.max(dp[i],ans);      }   if(ans==0)      return -1;   else       return ans;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.