Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | CPP Program to find the length of substring with maximum difference of zeros and ones in binary string . ; Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means all ones otherwise max_sum ; Driven Program
#include <iostream> NEW_LINE using namespace std ; int findLength ( string str , int n ) { int current_sum = 0 ; int max_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { current_sum += ( str [ i ] == '0' ? 1 : -1 ) ; if ( current_sum < 0 ) current_sum = 0 ; max_sum = max ( current_sum , max_sum ) ; } return max_sum == 0 ? -1 : max_sum ; } int main ( ) { string s = "11000010001" ; int n = 11 ; cout << findLength ( s , n ) << endl ; return 0 ; }