Length of the longest valid substring | Function to return the length of the longest valid substring ; Variables for left and right counter . maxlength to store the maximum length found so far ; Iterating the string from left to right ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Iterating the string from right to left ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Function call
def solve ( s , n ) : NEW_LINE INDENT left = 0 NEW_LINE right = 0 NEW_LINE maxlength = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT right += 1 NEW_LINE DEDENT if ( left == right ) : NEW_LINE INDENT maxlength = max ( maxlength , 2 * right ) NEW_LINE DEDENT elif ( right > left ) : NEW_LINE INDENT left = right = 0 NEW_LINE DEDENT DEDENT left = right = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT right += 1 NEW_LINE DEDENT if ( left == right ) : NEW_LINE INDENT maxlength = max ( maxlength , 2 * left ) NEW_LINE DEDENT elif ( left > right ) : NEW_LINE INDENT left = right = 0 NEW_LINE DEDENT DEDENT return maxlength NEW_LINE DEDENT print ( solve ( " ( ( ( ) ( ) ( ) ( ) ( ( ( ( ) ) " , 16 ) ) NEW_LINE