Longest Substring of 1 's after removing one character | Function to calculate the length of the longest substring of '1' s that can be obtained by deleting one character ; Add '0' at the end ; Iterator to traverse the string ; Stores maximum length of required substring ; Stores length of substring of '1' preceding the current character ; Stores length of substring of '1' succeeding the current character ; Counts number of '0' s ; Traverse the string S ; If current character is '1' ; Increase curr_one by one ; Otherwise ; Increment numberofZeros by one ; Count length of substring obtained y concatenating preceding and succeeding substrings of '1' ; Store maximum size in res ; Assign curr_one to prev_one ; Reset curr_one ; If string contains only one '0' ; Return the answer ; Driver code
function longestSubarray ( s ) { s += ' ' ; let i ; let res = 0 ; let prev_one = 0 ; let curr_one = 0 ; let numberOfZeros = 0 ; for ( i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' ' ) { curr_one += 1 ; } else { numberOfZeros += 1 ; prev_one += curr_one ; res = Math . max ( res , prev_one ) ; prev_one = curr_one ; curr_one = 0 ; } } if ( numberOfZeros == 1 ) { res -= 1 ; } return res ; } let S = " " ; document . write ( longestSubarray ( S ) ) ;