Iterate over the string starting from second index
for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' ) ' && i - longest [ i - 1 ] - 1 >= 0 && s [ i - longest [ i - 1 ] - 1 ] == ' ( ' ) { longest [ i ] = longest [ i - 1 ] + 2 + ( ( i - longest [ i - 1 ] - 2 >= 0 ) ? longest [ i - longest [ i - 1 ] - 2 ] : 0 ) ; curMax = max ( longest [ i ] , curMax ) ; } } return curMax ; }