problems / 181

Missing Brackets

easy bracket-sequences stack strings 1000 ms · 256 MB

Missing Brackets

Alice typed a long formula into her calculator, but she only copied its round brackets into her notes: a string s made of the characters ( and ). Some brackets got lost along the way, so the string may not be balanced any more.

A string of brackets is balanced if every ( can be paired with a ) somewhere after it, and every ) with a ( somewhere before it, with each bracket used in exactly one pair. For example, (())() and the empty string are balanced, while )(, (() and ()) are not.

Alice may insert brackets anywhere in the string: at the start, at the end, or between any two characters. She cannot delete or move the brackets already there. What is the smallest number of brackets she must insert to make the string balanced?

Input

The first line contains n (1 ≤ n ≤ 2·10^5), the length of the string.

The second line contains the string s of exactly n characters, each ( or ).

Output

Print one integer: the minimum number of brackets to insert.

Notes

In the first example, (() needs one ) at the end to become (()).

In the second example, ())(() has as many ( as ), yet it is not balanced: the third character ) has no ( left to pair with, and the ( at position 4 has no ) after it. Inserting a ( before the third character and a ) at the end gives ()()(()), so the answer is 2.

Example 1

Input

3
(()

Output

1

Example 2

Input

6
())(()

Output

2

Hints · reveal one at a time if you're stuck

Hint 1

Read the string from left to right. When you meet a ), can it always be paired with an earlier (? What has to happen when it can't?

Hint 2

Keep a count of the ( that are still waiting for their ). Each ) that finds the count at zero needs a new bracket, and so does every ( still waiting at the end.

report an issue Prefer your own editor? sooks prep 181 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.