Under construction

Still being built. Things may change

Hyunwook Is the Parenthesis King!!

Interview

Time limit2sMemory limit512 MB

Summary
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.

  1. () is a correct parenthesis string.
  2. If a string x is a correct parenthesis string, then (x) is also a correct parenthesis string.
  3. 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.

Examples2

  1. Example 1

    Input
    5
    (())(
    
    Expected output
    4
    
  2. Example 2

    Input
    14
    (()))()((()))(
    
    Expected output
    8