Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | 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 ; Driver Code
< ? php function findLength ( $ str , $ n ) { $ current_sum = 0 ; $ max_sum = 0 ; for ( $ 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 ; } $ s = "11000010001" ; $ n = 11 ; echo findLength ( $ s , $ n ) , " STRNEWLINE " ; ? >