Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Find the length of substring with maximum difference of zeros 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 string contains all ones otherwise max_sum ; Driver Code
function findLength ( str , n ) { let current_sum = 0 ; let max_sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { current_sum += ( str [ i ] == ' ' ? 1 : - 1 ) ; if ( current_sum < 0 ) { current_sum = 0 ; } max_sum = Math . max ( current_sum , max_sum ) ; } return max_sum == 0 ? - 1 : max_sum ; } let str = " " ; let n = str . length ; document . write ( findLength ( str , n ) ) ;