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
function solve ( s , n ) { let left = 0 , right = 0 , maxlength = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) left ++ ; else right ++ ; if ( left == right ) maxlength = max ( maxlength , 2 * right ) ; else if ( right > left ) left = right = 0 ; } left = right = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == ' ' ) left ++ ; else right ++ ; if ( left == right ) maxlength = Math . max ( maxlength , 2 * left ) ; else if ( left > right ) left = right = 0 ; } return maxlength ; } document . write ( solve ( " " , 16 ) ) ;