# Maximum difference of zeros and ones in binary string - (O(n) time) in C++

Given the task is to find a sub-string from a given binary string and then the maximum difference between the number of zeroes and the ones.

Let’s now understand what we have to do using an example −

## Input

str = “10010110”

## Output

2

## Explanation

In the sub-array from the position 1 to 4 (“0010”), the difference between the zeros and ones = 3 – 1 = 2 which is the maximum that can be found.

## Input

str = “00000”

## Output

5

## Approach used in the below program as follows

• In main() function create a string str to store the binary string. Also declare an array int arr[str.length()+1];

• Set all elements of arr[] = 0 by using memset(arr,0,sizeof(arr));

• Loop from j = 1 till j<= str.length()

• Check if(memset(arr,0,sizeof(arr)), if so then put arr[j]=max(arr[j-1]-1,-1);

• Else put arr[j]=max(arr[j-1]+1,1);

• Outside the loop print the maximum number by using *max_element(arr+1, arr+str.length()+1);

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
int main(){
string str = "10010110";
int arr[str.length()+1];
memset(arr,0,sizeof(arr));
for(int j=1;j<=str.length();j++){
if(str[j-1]=='1')
arr[j]=max(arr[j-1]-1,-1);
else
arr[j]=max(arr[j-1]+1,1);
}
cout<<*max_element(arr+1,arr+str.length()+1);
return 0;
}

## Output

2

Updated on: 04-Aug-2020

84 Views