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
def longestSubarray ( s ) : NEW_LINE INDENT s += '0' NEW_LINE i = 0 NEW_LINE res = 0 NEW_LINE prev_one = 0 NEW_LINE curr_one = 0 NEW_LINE numberOfZeros = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT curr_one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT numberOfZeros += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT prev_one += curr_one NEW_LINE res = max ( res , prev_one ) NEW_LINE prev_one = curr_one NEW_LINE curr_one = 0 NEW_LINE DEDENT ' NEW_LINE INDENT if ( numberOfZeros == 1 ) : NEW_LINE INDENT res -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1101" NEW_LINE print ( longestSubarray ( S ) ) NEW_LINE DEDENT