Balanced SubsequencesMedium

Balanced Subsequences

Medium+30 XP · +10 Aurastackhash mapgreedy

Anya loves the simple beauty of balanced sequences. She has a sequence of opening and closing brackets, represented by the characters '(' and ')'. A subsequence of this sequence is formed by deleting zero or more characters from the original sequence. Anya wants to find the length of the longest possible subsequence that is also a balanced bracket sequence. A bracket sequence is balanced if:

  1. It is empty.
  2. It can be written as AB, where A and B are balanced bracket sequences.
  3. It can be written as (A), where A is a balanced bracket sequence.

For example, "()()" and "(())()" are balanced, but ")(" and "(()" are not.

Help Anya find the length of the longest balanced subsequence she can form from her given bracket sequence.

Input

The first line contains a single integer N, the length of the bracket sequence. The second line contains a string of N characters, consisting only of '(' and ')'.

Output

A single integer: the length of the longest balanced subsequence.

Constraints

1 <= N <= 200000 The string contains only '(' and ')' characters.

Time limit 1 s (native code; slower languages get more)Memory 256 MB16 hidden tests

Example 1

Input
6
(()())
Output
6

The entire string is a balanced subsequence.

Example 2

Input
7
())((()))
Output
8

The longest balanced subsequence is "()(())" with length 6. The first ')' is unmatched.

Hints