Hyunwook Is the Parenthesis King!!
InterviewTime limit2sMemory limit512 MB
Given a string of parentheses, find the length of the longest contiguous substring that forms a correct parenthesis string.
- Level
Medium6 of 10
- Topics
- Stack, String, Prefix sum, Dynamic programming
- Solved
- No attempts yet
Problem
Among strings made up of the opening parenthesis '(' and the closing parenthesis ')', a string that satisfies the following conditions is called a correct parenthesis string.
- () is a correct parenthesis string.
- If a string x is a correct parenthesis string, then (x) is also a correct parenthesis string.
- If strings x and y are correct parenthesis strings, then xy is also a correct parenthesis string.
Hyunwook received a very long parenthesis string from a friend as a birthday present (why would anyone give this as a gift?). Since Hyunwook strongly dislikes strings that are not correct parenthesis strings, he wants to cut out a contiguous part of the received string to make a correct parenthesis string. And since longer is better, he wants to cut out as long a substring as possible. Help Hyunwook by writing a program that computes the length of the longest substring satisfying the conditions above.
Input
The first line gives the length n of the string (1 ≤ n ≤ 200,000).
The second line gives a string of length n consisting only of parentheses.
Output
Print the length of the longest substring of the given string that is a correct parenthesis string. If no substring is a correct parenthesis string, print 0.
Hint
In the first sample, the longest correct parenthesis string is (()), obtained by cutting 4 characters from the very beginning.
In the second sample, the longest correct parenthesis string is ()((())), obtained by cutting 8 characters starting from the 6th position.