You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'.

In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$).

Your task is to find the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints.

Recall what the regular bracket sequence is:

  "()" is regular bracket sequence;  if $s$ is regular bracket sequence then "(" + $s$ + ")" is regular bracket sequence;  if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence. 

For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($2 \le n \le 50$) — the length of $s$. It is guaranteed that $n$ is even. The second line of the test case containg the string $s$ consisting of $\frac{n}{2}$ opening and $\frac{n}{2}$ closing brackets.


-----Output-----

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints.


-----Example-----
Input
4
2
)(
4
()()
8
())()()(
10
)))((((())

Output
1
0
1
3



-----Note-----

In the first test case of the example, it is sufficient to move the first bracket to the end of the string.

In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.

In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

Difficulty: EASY
Tags: String algorithms

Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s1 = s.replace('()', '')
		s = s1
	print(len(s) // 2)


test_case = int(input())
for i in range(test_case):
	n = int(input())
	s = input()
	a = list()
	for i in s:
		if len(a) and a[-1] == '(' and (i == ')'):
			a.pop()
		else:
			a.append(i)
	print(len(a) // 2)


tt = int(input())
for loop in range(tt):
	n = int(input())
	s = input()
	d = 0
	ans = 0
	for i in s:
		if i == '(':
			d += 1
		else:
			d -= 1
		if d < 0:
			ans += 1
			d = 0
	print(ans)


t = int(input())
for you in range(t):
	n = int(input())
	s = input()
	curr = 0
	ans = 0
	for i in s:
		if i == '(':
			curr += 1
		else:
			curr -= 1
		if curr < 0:
			ans += 1
			curr = 0
	print(ans)


T = int(input())
for t in range(T):
	n = int(input())
	s = list(input())
	(c1, c2) = (0, 0)
	c = 0
	i = 0
	while i < n:
		if s[i] == '(':
			c1 += 1
		elif s[i] == ')':
			c2 += 1
		if c2 > c1:
			del s[i:i + 1]
			i -= 1
			s.append(')')
			c2 -= 1
			c += 1
		i += 1
	print(c)


t = int(input())
for m in range(t):
	n = int(input())
	s = input()
	stk = list()
	ans = 0
	for i in range(n):
		if s[i] == '(':
			stk.append('(')
		elif s[i] == ')':
			if len(stk) == 0:
				stk.append(')')
			elif stk[-1] == '(':
				stk.pop()
			elif stk[-1] == ')':
				stk.append(')')
	ans = len(stk) // 2
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	open_ = 0
	close_ = 0
	for i in s:
		if i == '(':
			open_ += 1
		elif i == ')':
			close_ += 1
		if i == ')':
			if open_ > 0:
				open_ -= 1
				close_ -= 1
	print(open_)
	t = t - 1


t = int(input())
for i in range(0, t):
	n = int(input())
	s = input()
	b = 0
	a = 0
	for i in range(0, n):
		if s[i] == '(':
			b += 1
		else:
			b -= 1
			if b < 0:
				b = 0
				a += 1
	print(a)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	for i in s:
		if i == '(':
			ans.append(i)
		elif len(ans) > 0 and ans[-1] == '(':
			del ans[-1]
		elif len(ans) > 0 and ans[-1] != '(':
			ans.append(i)
		elif i == ')':
			ans.append(i)
	print(len(ans) // 2)


def f(s, n):
	k = 0
	count = 0
	i = 0
	while i < n - count:
		if s[i] == '(':
			k += 1
		if s[i] == ')':
			if k > 0:
				k -= 1
			else:
				count += 1
				s = s[:i] + s[i + 1:] + ')'
				i -= 1
		i += 1
	return count

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input().replace('\n', '')
		print(f(s, n))
main()


import sys, math

def file():
	sys.stdin = open('input.py', 'r')
	sys.stdout = open('output.py', 'w')

def get_array():
	l = list(map(int, input().split()))
	return l

def main():
	for tt in range(int(input())):
		n = int(input())
		s = input()
		n = len(s)
		(c, ans) = (0, 0)
		i = 0
		while '()' in s:
			s = s.replace('()', '', 1)
		print(len(s) // 2)
main()


for _ in range(int(input())):
	n = int(input())
	s = input()[0:n]
	op = 0
	cl = 0
	bal = 0
	unbal = 0
	for i in s:
		if i == '(':
			op += 1
		if i == ')':
			if op > 0:
				bal += 1
				op -= 1
	print((len(s) - 2 * bal) // 2)


from sys import stdin, stdout
import math
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = input()
	arr = []
	for i in s:
		if len(arr) == 0:
			arr.append(i)
		elif arr[-1] == '(' and i == ')':
			arr.pop()
		else:
			arr.append(i)
	print(len(arr) // 2)


for _ in range(int(input())):
	n = int(input())
	l = list(input())
	c1 = 0
	for i in range(n):
		if l[i] == '(':
			c1 += 1
			if ')' in l[i:n]:
				for j in range(i + 1, n):
					if l[j] == ')':
						l[j] = '0'
						break
				c1 -= 1
	print(c1)


t = int(input())
for i in range(t):
	(n, s, a, k, m) = (int(input()), input(), [], 0, 0)
	for j in range(n):
		if s[j] == '(':
			a.append(j)
	for j in range(n):
		if a[-1] >= j:
			if s[j] == '(':
				m = m + 1
			elif m == 0:
				(m, k) = (0, k + 1)
				a.pop()
				if a == []:
					break
			else:
				m = m - 1
		else:
			break
	print(k)


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = set([])
	c = 0
	for i in range(n):
		if a[i] == '(':
			c += 1
		elif a[i] == ')':
			c -= 1
		if c < 0:
			b.add(c)
	print(len(b))


import sys
t = int(sys.stdin.readline().strip())
for _ in range(t):
	n = int(sys.stdin.readline().strip())
	s = sys.stdin.readline().strip()
	arr = [x for x in s]
	cur = 0
	ind = 0
	moves = 0
	while ind != n:
		if arr[ind] == '(':
			cur += 1
		else:
			cur -= 1
		if cur < 0:
			cur = 0
			arr.pop(ind)
			arr += [')']
			moves += 1
		else:
			ind += 1
	print(moves)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	st = []
	count = 0
	for i in range(n):
		if s[i] == '(':
			st.append('(')
		elif len(st) == 0:
			count += 1
		else:
			st.pop(0)
	count += len(st)
	print(count // 2)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	str1 = input()
	bra_open = 0
	bra_close = 0
	for i in range(0, n):
		if str1[i] == '(':
			bra_open += 1
		elif bra_open > 0:
			bra_open = bra_open - 1
	print(bra_open)


from sys import stdin

def readline():
	return stdin.readline()
tests = int(readline())

def solve(n, s):
	a = 0
	j = 0
	for i in range(0, n):
		if s[i] == '(':
			j -= 1
		else:
			j += 1
		if j > a:
			a += 1
	return a
for t in range(0, tests):
	n = int(readline().rstrip('\n'))
	s = readline().rstrip('\n')
	print(solve(n, s))


def is_valid_bracket_sequence(brackets):
	non_paired_opening_brackets = 0
	for _ in brackets:
		if _ == '(':
			non_paired_opening_brackets += 1
		else:
			non_paired_opening_brackets -= 1
		if non_paired_opening_brackets < 0:
			return False
	return True
number_of_tests = int(input())
for test in range(number_of_tests):
	length = int(input())
	brackets = input()
	moves = 0
	while not is_valid_bracket_sequence(brackets):
		for (index, _) in enumerate(brackets):
			if _ == ')':
				brackets = brackets[:index] + brackets[index + 1:] + ')'
				break
		moves += 1
	print(moves)


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	s = input().rstrip()
	stack = []
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif stack and stack[-1] == '(':
			stack.pop()
		else:
			stack.append(')')
	print(len(stack) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	str = input()
	o = c = a = 0
	for i in range(n):
		if str[i] == '(':
			o += 1
		elif o > 0:
			o -= 1
		else:
			a += 1
	print(a)


import sys
from bisect import bisect_left
from collections import defaultdict
input = lambda : sys.stdin.readline().rstrip()
R = lambda : map(int, input().split())
(T,) = R()
for _ in range(T):
	(n,) = R()
	s = input()
	ba = 0
	mx = 0
	for i in range(n):
		ba += 1 if s[i] == '(' else -1
		mx = max(mx, -ba)
	print(mx)


t = int(input())
while t:
	n = int(input())
	s = input()
	stack = []
	j = 0
	for i in s:
		if j == 0:
			stack.append(i)
			j += 1
		elif stack[-1] == '(' and i == ')':
			stack = stack[:-1]
			j -= 1
		else:
			stack.append(i)
			j += 1
	m = len(stack)
	print(m // 2)
	t -= 1


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	c = 0
	i = 0
	ans = 0
	while i < n:
		if s[i] == '(':
			c = c + 1
		if s[i] == ')' and c <= 0:
			ans = ans + 1
		if s[i] == ')' and c > 0:
			c = c - 1
		i = i + 1
	print((ans + c) // 2)
	t = t - 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(s.count(')'))


for _ in range(int(input())):
	n = int(input())
	s = input()
	x = 0
	c = 0
	for i in range(n):
		if s[i] == '(':
			x += 1
		else:
			x -= 1
		if x < 0:
			c += 1
			x = 0
	print(c)


def biu(lista):
	res = False
	for i in range(0, len(lista) - 1):
		if lista[i] == '(' and lista[i + 1] == ')':
			lista.pop(i + 1)
			lista.pop(i)
			res = True
			break
	return res
t = int(input())
for e in range(t):
	tam = int(input())
	ent = input()
	lista = []
	for e in ent:
		lista.append(e)
	while biu(lista):
		continue
	print(len(lista) // 2)


n = int(input())
for _ in range(0, n):
	length = int(input())
	s = input()
	opened = 0
	regular_brackets = 0
	for bracket in s:
		if bracket == '(':
			opened += 1
		elif opened > 0:
			opened -= 1
			regular_brackets += 2
	print(int((length - regular_brackets) / 2))


t = int(input())
while t > 0:
	n = int(input())
	l = input()
	sum = 0
	m = 100000
	for i in range(len(l)):
		if l[i] == '(':
			sum += 1
		elif l[i] == ')':
			sum -= 1
		m = min(m, sum)
	print(-m)
	t -= 1


t = int(input())
ans = []
for _ in range(t):
	input()
	line = str(input())
	result = ''
	balance = 0
	ans.append(0)
	i = 0
	while i < len(line):
		if line[i] == '(':
			balance = balance + 1
			i = i + 1
		elif balance > 0:
			balance = balance - 1
			i = i + 1
		else:
			ans[-1] = ans[-1] + 1
			line = line[:i] + line[i + 1:] + line[i]
for i in ans:
	print(i)


testcase = int(input())
for _ in range(testcase):
	n = int(input())
	a = input()
	stack = []
	counter = 0
	for b in a:
		if b == '(':
			stack.append(b)
		elif len(stack) > 0 and b == ')':
			stack.pop()
		else:
			counter += 1
	res = (counter + len(stack)) // 2
	print(res)


def check(my_string):
	global s1
	s1 = my_string
	brackets = ['()']
	while any((x in s1 for x in brackets)):
		for br in brackets:
			s1 = s1.replace(br, '')
	return not s1
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	count1 = 0
	count2 = 0
	if check(s):
		print(0)
	else:
		for i in range(len(s1)):
			if s1[i] == ')':
				count2 += 1
			else:
				count1 += 1
		if count1 == count2:
			print(count1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	bal = 0
	minbal = 0
	for c in s:
		if c == '(':
			bal += 1
		else:
			bal -= 1
		if bal < minbal:
			minbal = bal
	print(abs(minbal))


import sys, collections, math

def in_out():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	for i in range(n):
		if not stack:
			stack.append(s[i])
		elif s[i] == '(':
			stack.append(s[i])
		elif s[i] == ')':
			if stack[-1] == '(':
				stack.pop()
			else:
				stack.append(s[i])
	print(len(stack) // 2)


t = int(input())
p = 1
while p <= t:
	n = int(input())
	s = input()
	i = 0
	cnt = 0
	ans = 0
	while i < n:
		if s[i] == '(':
			cnt += 1
		else:
			cnt -= 1
			if cnt < 0:
				ans += 1
				cnt = 0
		i += 1
	print(ans)
	p += 1


def min_reversal_better(string):
	li = []
	count = 0
	if len(string) % 2 != 0:
		return -1
	for i in string:
		if i == '(':
			li.append(i)
		elif i == ')':
			if len(li) > 0 and li[-1] == '(':
				li.pop()
			else:
				li.append(i)
	while len(li) > 0:
		c1 = li.pop()
		c2 = li.pop()
		count += 1
	return count
n = int(input())
li1 = []
for i in range(n):
	a = int(input())
	k = input()
	li1.append(k)
for i in li1:
	print(min_reversal_better(i))


def solve(s):
	balance = 0
	ans = 0
	for ch in s:
		if ch == '(':
			balance += 1
		elif ch == ')':
			balance -= 1
		else:
			raise RuntimeError('...')
		ans = min(ans, balance)
	return -ans
for _ in range(int(input())):
	_ = int(input())
	s = input()
	print(solve(s))


def process():
	int(input())
	strg = input()
	mn = float('inf')
	s = 0
	dt = {'(': 1, ')': -1}
	for ch in strg:
		s += dt[ch]
		mn = min(s, mn)
	print(abs(mn))
for i in range(int(input())):
	process()


import sys
import bisect as b
import math
from collections import defaultdict as dd
input = sys.stdin.readline

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
for _ in range(inin()):
	n = inin()
	s = sin().strip()
	c = o = ans = 0
	for i in s:
		if i == ')':
			c += 1
		else:
			if c > o:
				ans += c - o
				c = o
			o += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 1
	while c > 0:
		c = s.count('()')
		s = s.replace('()', '')
	print(s.count('('))


from collections import defaultdict as dfd
import math
import sys
import heapq

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def main():
	for _ in range(int(input())):
		N = II()
		A = input()
		val = []
		co = 0
		for i in range(len(A)):
			if A[i] == '(':
				val.append(A[i])
			elif A[i] == ')':
				if len(val) > 0:
					if val[-1] == '(':
						val.pop()
					else:
						val.append(A[i])
						co += 1
				else:
					val.append(A[i])
					co += 1
		print(co)
main()


t = int(input())
for _ in range(t):
	x = int(input())
	n = list(input())
	count = 0
	res = float('inf')
	for i in n:
		if i == '(':
			count += 1
		else:
			count -= 1
		res = min(res, count)
	print(abs(res))


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	stack = []
	count = 0
	for i in range(n):
		if string[i] == '(':
			stack.append('(')
		if string[i] == ')' and len(stack) > 0:
			stack.pop()
	print(len(stack))


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	p = ''
	q = ''
	for i in range(n):
		if s[i] == '(':
			c += 1
			p += s[i]
		elif c > 0:
			c = c - 1
			p += s[i]
		else:
			q += s[i]
	print(len(q))


ans = []
for _ in range(int(input())):
	input()
	s = input()
	i = 0
	j = 0
	a = 0
	for b in s:
		if b == '(':
			i += 1
		else:
			j += 1
		if i < j:
			a += 1
			j -= 1
	ans.append(str(a))
print('\n'.join(ans))


test = int(input())
for i in range(test):
	tamanho = int(input())
	n = list(input())
	qtd = 0
	balance = 0
	prefix_sum = [0] * tamanho
	for j in range(tamanho):
		if n[j] == '(':
			balance += 1
		else:
			balance -= 1
		if balance < 0:
			balance = 0
			qtd += 1
	print(qtd)


for _ in range(int(input())):
	n = int(input())
	s = [i for i in input()]
	l1 = []
	l2 = []
	for ii in s:
		if ii == '(':
			l1.append(ii)
		elif ii == ')' and len(l1) != 0:
			l1.pop(-1)
		elif ii == ')' and len(l1) == 0:
			l2.append(ii)
		else:
			pass
	print(len(l1))


import sys
RI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
from collections import defaultdict as df
import copy
import math
t = int(input().strip())
for _ in range(t):
	n = int(input().strip())
	s = input().strip()
	temp = 0
	ans = 0
	for i in s:
		if i == '(':
			temp += 1
		else:
			temp -= 1
			if temp < 0:
				temp += 1
				ans += 1
	print(ans)


t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	low = 0
	ht = 0
	for i in range(n):
		if s[i] == ')':
			ht -= 1
		else:
			ht += 1
		low = min(low, ht)
	ans = -low
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = [i for i in input()]
	c = 1
	while c != 0:
		c = 0
		i = 0
		while i < len(l) - 1:
			if l[i:i + 2] == ['(', ')']:
				l.pop(i)
				l.pop(i)
				i = max(i - 1, 0)
				c += 1
			else:
				i += 1
	print(len(l) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	o = 0
	for x in s:
		if x == '(':
			o += 1
		elif x == ')' and o > 0:
			o -= 1
	print(o)


import sys
input = sys.stdin.readline

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()

def lower_letters():
	lowercase = [chr(i) for i in range(97, 97 + 26)]
	return lowercase

def how_frequent(lis):
	last = None
	count = []
	each = 1
	for i in range(len(lis)):
		if last != None:
			last = lis[i - 1]
		if last == lis[i]:
			each += 1
		else:
			count.append(each)
			each = 0
		last = lis[i]
	return max(count)

def upper_letters():
	uppercase = [chr(i) for i in range(65, 65 + 26)]
	return uppercase
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	extra = 0
	opening = 0
	closing = 0
	flag = False
	for i in range(n):
		if s[i] == '(':
			opening += 1
			if flag == True:
				closing = 0
				opening = 1
				flag = False
		elif s[i] == ')':
			closing += 1
			if closing > opening:
				flag = True
				extra += 1
	print(extra)


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


for c in range(int(input())):
	a = int(input())
	b = input()
	l = []
	i = 0
	for t in b:
		l.append(t)
	for y in range(a):
		for n in range(y, a):
			if l[y] == '(' and l[n] == ')':
				l[y] = 0
				l[n] = 0
				continue
	i = l.count('(')
	print(i)


def f(s):
	currentoffset = 0
	biggestoffset = 0
	for char in s:
		if char == ')':
			currentoffset += 1
			biggestoffset = max(biggestoffset, currentoffset)
		else:
			currentoffset -= 1
	return biggestoffset
numberofcases = int(input())
for _ in range(numberofcases):
	n = int(input())
	print(f(input()))


def solve1():
	n = int(input())
	s = input()
	cnt = 0
	ans = 50
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		ans = min(ans, cnt)
	print(-1 * ans)
for _ in range(int(input())):
	solve1()


ans = []
q = int(input())

def res():
	global ans
	n = int(input())
	a = list(input())
	b = True
	while b:
		b = False
		for x in range(len(a) - 1):
			if a[x] == '(' and a[x + 1] == ')':
				a.pop(x)
				a.pop(x)
				b = True
				break
	ans.append(str(len(a) // 2))
for x in range(q):
	res()
print('\n'.join(ans))


t = int(input())
while t != 0:
	input()
	output = 0
	s = input()
	c = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c == -1:
			output += 1
			c = 0
	print(output)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	open = 0
	close = 0
	for i in range(len(s)):
		if s[i] == '(':
			open += 1
		elif s[i] == ')':
			if open > 0:
				open -= 1
				pass
			else:
				close += 1
	print(close)


for test in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	coun = 0
	for i in s:
		if i == '(':
			coun += 1
		elif i == ')' and coun > 0:
			coun -= 1
		else:
			ans += 1
	print(ans)


import math

def inp_n():
	return int(input())

def inp_list():
	return list(map(int, input().split()))

def inp_mul_num():
	return map(int, input().split())

def is_odd(n):
	if n & 1:
		return True
	return False
for _ in range(inp_n()):
	n = inp_n()
	s = input()
	l = []
	for el in s:
		if el == '(':
			l.insert(0, el)
		elif len(l) != 0:
			l.pop()
	print(len(l))


t = int(input())
for v in range(t):
	n = int(input())
	s = input()
	nob = 0
	for i in range(n):
		if s[i] == '(':
			nob += 1
		if s[i] == ')' and nob >= 1:
			nob -= 1
	print(nob)


for i in range(int(input())):
	a = int(input())
	s = input()
	ans = 0
	c = 0
	for s1 in s:
		if s1 == ')':
			c = c + 1
		else:
			c = c - 1
		ans = max(c, ans)
	print(ans)


t = int(input())
while t:
	n = int(input())
	s = input()
	close = []
	open = []
	count = 0
	for i in s:
		if i == ')':
			if len(open) != 0:
				open.pop(len(open) - 1)
			else:
				close.append(i)
		if i == '(':
			open.append(i)
	print(len(close))
	t = t - 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	s1 = 0
	s2 = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			s1 += 1
		else:
			s2 += 1
		if s2 > s1:
			ans = max(ans, s2 - s1)
	print(ans)


import sys

def I():
	return list(map(int, input().split()))

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	n = int(input())
	s = [i for i in input()]
	moves = 0
	while True:
		balance = 0
		for i in range(n):
			if s[i] == '(':
				balance += 1
			else:
				balance -= 1
			if balance < 0:
				break
		if balance == 0:
			break
		s.append(s.pop(i))
		moves += 1
	print(moves)


def get_arry():
	return list(map(int, input().split()))

def get_int():
	return int(input())

def get_input():
	return input()

def areParanthesisBalanced(expr):
	stack = []
	cnt = 0
	for char in expr:
		if char in ['(', '{', '[']:
			stack.append(char)
		elif len(stack) != 0:
			current_char = stack[-1]
			if current_char == '(':
				if char == ')':
					stack.pop()
				else:
					cnt += 1
		else:
			cnt += 1
	return (cnt + len(stack)) // 2

def main():
	for _ in range(int(input())):
		m = get_int()
		n = get_input()
		print(areParanthesisBalanced(n))
main()


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	c = 0
	count = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
			if c < 0:
				count += 1
				c = 0
	print(count)


def main():
	t = int(input())
	for tt in range(t):
		n = int(input())
		a = list(map(str, input()))
		i = 0
		while i < len(a) - 1:
			if a[i] == '(' and a[i + 1] == ')':
				a[i] = str(1)
				a[i + 1] = str(2)
				a.remove(a[i])
				a.remove(a[i])
				i = -1
			if len(a) == 0:
				break
			i = i + 1
		print(len(a) // 2)
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	m = 0
	num = 0
	for i in range(len(s)):
		if s[i] == '(':
			num += 1
		elif num == 0:
			m += 1
		else:
			num -= 1
	print(m)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	for i in s:
		if i == '(':
			cnt += 1
		elif cnt > 0:
			cnt -= 1
	print(cnt)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(b, ans) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			b += 1
		else:
			b -= 1
			if b < 0:
				b = 0
				ans += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	m = 0
	for j in range(n):
		if s[j] == ')':
			c += 1
			o = s[0:j].count('(')
			if o < c:
				c -= 1
				m += 1
	print(m)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	closed = 0
	opened = 0
	net_bal = 0
	for j in range(n):
		if s[j] == '(':
			opened += 1
		elif opened > 0:
			opened -= 1
		else:
			net_bal += 1
	print(net_bal)


t = int(input())
for _ in range(t):
	xc = int(input())
	x = input()
	l = []
	for i in x:
		if i == '(':
			l.append('(')
		elif l:
			if l[-1] == '(':
				l.remove(l[-1])
			else:
				l.append(i)
		else:
			l.append(i)
	print(len(l) // 2)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	n = ri()
	s = input()
	depth = 0
	moves = 0
	for c in s:
		if c == '(':
			depth += 1
		elif depth == 0:
			moves += 1
		else:
			depth -= 1
	print(moves)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = 0
	ans = 0
	for i in s:
		if i == '(':
			stack += 1
		else:
			stack -= 1
		if stack < 0:
			ans += 1
			stack = 0
	print(ans)


def main():
	n = int(input())
	s = input()
	st = [s[0]]
	for i in range(1, n):
		if s[i] == ')':
			if len(st) != 0 and st[-1] == '(':
				st.pop()
			else:
				st.append(s[i])
		else:
			st.append(s[i])
	print(len(st) // 2)
t = int(input())
while t > 0:
	t -= 1
	main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = 0
	count = 0
	for i in range(len(s)):
		if s[i] == '(':
			stack += 1
		elif stack == 0:
			count += 1
		else:
			stack -= 1
	print(count)


n = int(input())
for i in range(n):
	input()
	s = input()
	stack = []
	c = 0
	for char in s:
		if char == '(':
			stack.append('(')
		elif char == ')':
			if stack != []:
				stack.remove('(')
			else:
				c += 1
	print(c)


t = int(input())
while t != 0:
	n = int(input())
	s = input()
	sum1 = 0
	count = 0
	for i in range(n):
		if s[i] == '(':
			sum1 += 1
		else:
			sum1 -= 1
		if sum1 < 0:
			sum1 += 1
			count += 1
	print(count)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	cnt = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			ans = max(ans, abs(cnt))
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	openb = 0
	closeb = 0
	for i in range(n):
		if s[i] == '(':
			openb += 1
		elif s[i] == ')':
			if openb > 0:
				openb -= 1
			else:
				closeb += 1
	print(closeb)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = deque([])
	ans = 0
	for i in range(n):
		if s[i] == '(':
			stack.append(s[i])
		elif len(stack) != 0:
			stack.pop()
		else:
			ans += 1
	print(ans)


def brackets(n, s):
	i = 0
	op = 0
	clo = 0
	onlyclo = 0
	arr = []
	while i < len(s):
		if op - clo == 0 and s[i] == ')':
			onlyclo += 1
		elif s[i] == '(':
			op += 1
		else:
			clo += 1
		i += 1
	print(onlyclo)
for _ in range(int(input())):
	n = int(input())
	s = input()
	brackets(n, s)


def factorial(n):
	if n == 0:
		return 1
	else:
		return n * factorial(n - 1)

def FibRecursion(n):
	if n <= 1:
		return n
	else:
		return FibRecursion(n - 1) + FibRecursion(n - 2)

def methoding(num, strr):
	try:
		count = 0
		for x in strr:
			if x == '(':
				count += 1
			if x == ')':
				if count > 0:
					count -= 1
		if count > 0:
			print(count)
		else:
			print(count * -1)
	except:
		pass

def factorial(n):
	if n == 0:
		return 1
	else:
		return n * factorial(n - 1)

def FibRecursion(n):
	if n <= 1:
		return n
	else:
		return FibRecursion(n - 1) + FibRecursion(n - 2)
T = input()
tc = int(T)
while tc:
	tc -= 1
	N = int(input())
	S = input()[:N]
	methoding(N, S)

def FibRecursion(n):
	if n <= 1:
		return n
	else:
		return FibRecursion(n - 1) + FibRecursion(n - 2)


T = int(input())
while T > 0:
	T -= 1
	N = int(input())
	S = input()
	A = []
	B = []
	c = 0
	for i in S:
		if i == '(':
			A.append(i)
		elif len(A) == 0:
			c += 1
		elif A[len(A) - 1] == '(':
			A.pop()
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stk = []
	for i in s:
		if i == '(':
			stk.append(i)
		elif stk == [] or stk[-1] == ')':
			stk.append(i)
		else:
			stk.pop()
	print(len(stk) // 2)


def solution(s):
	arr = []
	for i in range(len(s)):
		if s[i] == '(':
			arr.append(s[i])
		if s[i] == ')':
			if len(arr) == 0:
				arr.append(s[i])
			elif arr[-1] == '(':
				arr.pop()
			elif arr[-1] == ')':
				arr.append(s[i])
	return len(arr) // 2
for _ in range(int(input())):
	n = int(input())
	s = input()
	print(solution(s))


for i1 in range(int(input())):
	n = int(input())
	s = input()
	s = s.replace('\r', '')
	stack = []
	top = -1
	for i in s:
		if i == '(':
			stack.append(i)
			top = stack[-1]
		elif top == '(':
			stack = stack[:-1]
			if len(stack) == 0:
				top = -1
			else:
				top = stack[-1]
		else:
			stack.append(i)
	print(len(stack) // 2)


from sys import stdin, stdout
import math, cmath
import itertools

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_list():
	return list(map(int, stdin.readline().strip().split()))
t = int(input())
for i in range(t):
	n = stdin.readline()
	s = stdin.readline()
	(c1, c2) = (0, 0)
	for i in s:
		if i == '(':
			c1 += 1
		elif i == ')':
			c1 -= 1
		if c1 < 0:
			c2 += 1
			c1 = 0
	print(c2)


from sys import stdin as sin
for _ in range(int(sin.readline())):
	n = int(sin.readline())
	br = list(sin.readline())
	b = list()
	cnt = 0
	for i in br:
		if len(b) == 0:
			b.append(i)
		elif i != b[-1] and b[-1] == '(':
			b.pop(-1)
		else:
			b.append(i)
	print(b.count(')'))


import sys
import math
data = sys.stdin.readlines()
for i in range(int(data[0])):
	s = data[2 * i + 2]
	s = list(s[:len(s) - 1])
	a = 0
	b = 0
	resp = 0
	for j in range(len(s)):
		if s[j] == '(':
			a += 1
		else:
			b += 1
			if b > a:
				resp += 1
				b -= 1
	print(resp)


n = int(input())
for i in range(n):
	len = int(input())
	s = input()
	c = 0
	ct = 0
	for j in s:
		if j == ')':
			c -= 1
		else:
			c += 1
		if c < 0:
			ct += 1
			c = 0
	print(ct)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	while s.count('()') != 0:
		s = s.replace('()', '')
	print(len(s) // 2)


def helper(s, n):
	if n < 2:
		return 0
	stack = []
	for char in s:
		if char == '(':
			stack.append(char)
		elif stack and stack[-1] == '(':
			stack.pop()
		else:
			stack.append(char)
	return len(stack) // 2
for _ in range(int(input())):
	n = int(input())
	s = input()
	print(helper(s, n))


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import deque

def main():
	t = int(input())
	for _ in range(t):
		l = int(input())
		s = input()
		n = 0
		res = 0
		for i in range(l):
			if s[i] == '(':
				n += 1
			elif n:
				n -= 1
			else:
				res += 1
		print(res)
main()


for _ in range(int(input())):
	n = int(input())
	st = input()
	operation = 0
	flip = 0
	for i in range(n):
		if st[i] == '(':
			flip += 1
		else:
			flip -= 1
		if flip < 0:
			operation += 1
			flip = 0
	print(operation)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(councils, a, k):
	summ = 0
	for x in a:
		summ += min(x, councils)
	return summ // councils >= k
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	n = int(input())
	brackets = input().rstrip()
	st = []
	c = 0
	i = 0
	while i < n:
		if brackets[i] == '(':
			st.append(1)
		elif brackets[i] == ')' and len(st) > 0:
			st.pop()
		elif brackets[i] == ')' and len(st) == 0:
			c += 1
			brackets = brackets[:i] + brackets[i + 1:] + brackets[i]
			i -= 1
		i += 1
	print(c)
for _ in range(int(input())):
	solve()


t = int(input())
for k in range(t):
	n = int(input())
	l = list(str(input()))
	(a, b, c, d) = (0, 0, 0, 0)
	for i in range(n):
		if l[i] == '(':
			a += 1
		elif l[i] == ')' and a > 0:
			a -= 1
		elif l[i] == ')' and a == 0:
			b += 1
	for i in range(n - 1, -1, -1):
		if l[i] == ')':
			c += 1
		elif l[i] == '(' and c > 0:
			c -= 1
		elif l[i] == '(' and c == 0:
			d += 1
	print(min(b, d))


for i in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	x = 0
	for i in range(len(s)):
		if s[i] == '(':
			x += 1
		elif x > 0:
			x -= 1
		else:
			c += 1
	print(c)


n = int(input())
for i in range(n):
	ls = int(input())
	s = input()
	m = [1 - 2 * (s[0] == '(')] * ls
	for j in range(1, ls):
		if s[j] == '(':
			m[j] = m[j - 1] - 1
		else:
			m[j] = m[j - 1] + 1
	print(max(max(m), 0))


for _ in range(int(input())):
	n = int(input())
	s = input()
	counto = 0
	countc = 0
	count = 0
	i = 0
	while i < n - 1:
		if s[i] == '(':
			counto += 1
		else:
			countc += 1
		if countc > counto:
			t = s[i]
			s = s[:i] + s[i + 1:] + t
			count += 1
			countc -= 1
		else:
			i += 1
	print(count)


import math
from collections import deque
from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(input().strip())
	left = [0] * n
	right = [0] * n
	opened = 0
	closed = 0
	for i in range(n):
		if arr[i] == '(':
			opened += 1
		elif opened > 0:
			opened -= 1
		else:
			closed += 1
		left[i] = (opened, closed)
	print(min(left[-1]))


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	S = input()
	q = deque([])
	ans = 0
	for s in S:
		if s == '(':
			q.append(s)
		elif not q:
			ans += 1
		else:
			q.popleft()
	print(ans)


t = int(input())
while t > 0:
	(ct, op) = (0, 0)
	n = int(input())
	str = input()
	for i in str:
		if i == '(':
			ct = ct + 1
		elif ct > 0:
			ct = ct - 1
	print(ct)
	t = t - 1


for _ in range(int(input())):
	d = int(input())
	e = input()
	c = 0
	depth = 0
	for i in e:
		if i == '(':
			depth += 1
		elif i == ')':
			depth -= 1
		if depth == -1:
			c += 1
			depth = 0
	print(c)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
tc = ii1()
for _ in range(tc):
	n = ii1()
	s = is1()
	stack = []
	count = 0
	while True:
		for i in range(n):
			if s[i] == '(':
				stack.append('(')
			elif len(stack) and stack[-1] == '(':
				stack.pop()
			else:
				s = s[:i] + s[i + 1:] + ')'
				stack = []
				count += 1
				break
		else:
			break
	print(count)


def solve():
	n = int(input())
	s = input()
	stk = []
	top = -1
	for br in s:
		if top > -1 and stk[-1] == '(' and (br == ')'):
			stk.pop()
			top -= 1
		else:
			top += 1
			stk.append(br)
	return len(stk) // 2

def main():
	t = int(input())
	while t:
		print(solve())
		t -= 1
main()


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
t = int(fastinput())
while t:
	t -= 1
	n = int(fastinput())
	s = input()
	stack = []
	m = 0
	for i in s:
		if i == '(':
			stack.append('(')
		elif stack:
			if stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
		else:
			stack.append(')')
	print(stack.count(')'))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	i = 0
	j = n - 1
	front = 0
	last = 0
	ans = 0
	while i < j:
		if s[i] == '(':
			front += 1
			i += 1
		else:
			front -= 1
			if front >= 0:
				i += 1
		if s[j] == ')':
			last += 1
			j -= 1
		else:
			last -= 1
			if last >= 0:
				j -= 1
		if front < 0 and last < 0:
			ans += 1
			front = 0
			last = 0
			i += 1
			j -= 1
	print(ans)


def stend(sample, i):
	sample = sample[:i] + sample[i + 1:] + sample[i]
	return sample

def bprob3(sample, size):
	i = 0
	lb = 0
	rb = 0
	d = 0
	count = 0
	while i < size:
		if sample[i] == '(':
			lb = lb + 1
			d = lb - rb
			i = i + 1
		elif sample[i] == ')':
			rb = rb + 1
			d = lb - rb
			if d == 0:
				lb = 0
				rb = 0
				i = i + 1
			elif d < 0:
				sample = stend(sample, i)
				lb = 0
				rb = 0
				count = count + 1
			elif d > 0:
				i = i + 1
	return count

def main():
	t = int(input())
	b = 0
	while b < t:
		size = int(input())
		sample = input()
		print(bprob3(sample, size))
		b = b + 1
main()


for s in [*open(0)][2::2]:
	r = c = 0
	for x in s:
		c += 2 * ord(x) - 81
		r += c > r
	print(r)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		n = N()
		s = input()
		l = 0
		c = 0
		for i in s:
			if i == '(':
				l += 1
			elif l > 0:
				l -= 1
				c += 1
		print((n - c * 2) // 2)
main()


for _ in range(int(input())):
	x = int(input())
	y = input()
	count = 0
	value = 0
	for i in range(x):
		if y[i] == '(':
			value += 1
		if y[i] == ')':
			if value == 0:
				count += 1
			else:
				value -= 1
	print(count)


t = int(input())
for _ in range(t):
	l = int(input())
	s = input()
	stack = []
	for i in range(l):
		stack.append(s[i])
		try:
			if stack[-1] == ')' and stack[-2] == '(':
				stack.pop()
				stack.pop()
		except:
			continue
	ans = len(stack) // 2
	print(ans)


import math
import os
import random
import re
import sys
import heapq
import random
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	arr = list(input())
	moves = 0
	st = 0
	balance = 0
	for a in arr:
		if a == '(':
			st += 1
		elif st > 0:
			st -= 1
		else:
			moves += 1
	print(moves)


for i in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	j = 0
	count = 0
	ans = 0
	while j < len(s):
		if count == 0 and s[j] == ')':
			s += ')'
			ans += 1
		elif count >= 0 and s[j] == '(':
			count += 1
		else:
			count -= 1
		j += 1
	print(ans)


from math import *
from itertools import *
from collections import *

def ii():
	return int(input())

def mas():
	return [int(i) for i in input().split()]

def mapis():
	return map(int, input().split())
INF = 1000000000.0 + 1

def solve():
	n = ii()
	s = input()
	stek = []
	k = 0
	for i in range(n):
		if s[i] == '(':
			stek.append(s[i])
		elif stek:
			stek.pop()
		else:
			k += 1
	print(k)

def main():
	t = ii()
	while t:
		solve()
		t -= 1
main()


n = int(input())
for i in range(n):
	k = int(input())
	que2 = que = input()
	ans = 0
	while True:
		while '()' in que:
			que = que.replace('()', '')
		if ')(' in que:
			que = que.replace(')(', '')
			ans += 1
		if que == '':
			break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	for i in s:
		if cnt == 0 and i == ')':
			continue
		elif i == '(':
			cnt += 1
		else:
			cnt -= 1
	print(cnt)


from __future__ import division, print_function
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
from collections import Counter
import collections
import math
import heapq
import re

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def most_frequent(list):
	return max(set(list), key=list.count)

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def Convert(string):
	li = list(string.split(''))
	return li

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
prime = []
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j

def main():
	for _ in range(inin()):
		n = inin()
		s = list(sin())
		a = '('
		b = ')'
		arr = []
		temp = []
		for i in range(n):
			if s[i] == a:
				arr.append(s[i])
			elif len(arr) > 0:
				arr.pop()
			else:
				temp.append(s[i])
		print(len(temp))
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def get_balance(n, s):
	balance = 0
	min_balance = n + 1
	for i in range(n):
		if s[i] == ')':
			balance -= 1
			min_balance = min(min_balance, balance)
		else:
			balance += 1
	if min_balance < 0:
		return abs(min_balance)
	else:
		return 0
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(get_balance(n, s))


t = int(input())
for i in range(t):
	a = int(input())
	s = str(input())
	m = 0
	d = 0
	for i in range(a):
		if s[i] == ')':
			m -= 1
		else:
			m += 1
		if m < d:
			d = m
	print(abs(d))


def list_input():
	return list(map(int, input().split()))

def multiple_input():
	return map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	ans = 0
	for i in s:
		if i == '(':
			stack.append(i)
		elif len(stack) == 0:
			ans += 1
		else:
			stack.pop()
	print(ans)


t = int(input())
strings = []
for i in range(t):
	n = int(input())
	s = input()
	strings.append(s)
for s in strings:
	stack = []
	for b in s:
		if b == '(':
			stack.append(b)
		elif b == ')':
			if len(stack) == 0:
				stack.append(b)
			elif stack[len(stack) - 1] == '(':
				stack.pop(-1)
			else:
				stack.append(b)
	print(len(stack) // 2)


for x in range(int(input())):
	n = int(input())
	nawiasy = input()
	bledy = 0
	(i_otw, i_zam) = (0, 0)
	for y in nawiasy:
		if y == '(':
			i_otw += 1
		else:
			i_zam += 1
		if i_zam > i_otw:
			bledy += 1
			i_zam -= 1
	print(bledy)


t = int(input())
for ts in range(t):
	n = int(input())
	s = input()
	o = 0
	sol = 0
	for i in s:
		if i == '(':
			o += 1
		elif o == 0:
			sol += 1
		else:
			o -= 1
	print(sol)


t = int(input())
for _ in range(t):
	lenofseq = int(input())
	bracketseq = input()
	while '()' in bracketseq:
		bracketseq = bracketseq.replace('()', '')
	print(len(bracketseq) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	val = 0
	lis = []
	for c in s:
		if c == '(':
			val += 1
		else:
			val -= 1
		lis.append(val)
	ans = abs(min(lis))
	print(ans)


for _ in range(int(input())):
	stack = []
	brackets = []
	n = int(input())
	s = input()
	for char in s:
		if char == '(':
			stack.append(char)
		elif not stack:
			brackets.append(char)
		else:
			stack_br = stack.pop()
			if stack_br == char:
				brackets.append(char)
	if stack:
		for i in stack:
			brackets.append(i)
	print(int(len(brackets) / 2))


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	S = input()
	ans = 0
	cntl = cntr = 0
	for s in S:
		if s == '(':
			cntl += 1
		else:
			cntr += 1
		if cntr > cntl:
			cntr -= 1
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	ans = 0
	for i in s:
		if i == ')' and len(st) == 0:
			ans += 1
		elif i == ')':
			st.pop()
		else:
			st.append(i)
	ans2 = 0
	st = []
	for i in s[::-1]:
		if i == '(' and len(st) == 0:
			ans2 += 1
		elif i == '(':
			st.pop()
		else:
			st.append(i)
	print(min(ans, ans2))


for _ in range(int(input())):
	n = int(input())
	s = input()
	(start, end) = (0, 0)
	for i in s:
		if i == '(':
			start += 1
		elif start > 0:
			start -= 1
		else:
			end += 1
	print(end)


def fun(p):
	c = 0
	m = c
	for i in p:
		if i == ')':
			c += 1
			if m < c:
				m = c
		else:
			c -= 1
	return m
x = int(input())
s = []
for i in range(x):
	t = input()
	s.append(input())
for i in range(x):
	print(fun(s[i]))


numberOfTc = int(input())
for ctr in range(1, numberOfTc + 1):
	N = int(input())
	brackets = list(input().strip())
	st = []
	for i in brackets:
		if i == '(':
			st.append(i)
		elif len(st) > 0:
			st.pop()
	print(len(st))


for _ in range(int(input())):
	n = int(input())
	s = input()
	op = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			op += 1
		elif op > 0:
			op -= 1
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	str = list(input())
	count = 0
	count1 = 0
	count2 = 0
	for i in str:
		if i == '(':
			count1 += 1
		else:
			count2 += 1
		if count2 > count1:
			count1 = 0
			count2 = 0
			count += 1
	print(count)


n = int(input())
while n:
	n -= 1
	a = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


def moves(s):
	sign = {'(': 1, ')': -1}
	cs = list(s)
	counter = 0
	to_swap = True
	while to_swap:
		to_swap = False
		swap_pos = -1
		tracker = 0
		for (i, b) in enumerate(cs):
			tracker += sign[b]
			if tracker == -1:
				to_swap = True
				swap_pos = i
				break
		if to_swap:
			b = cs.pop(swap_pos)
			cs.append(b)
			counter += 1
	return counter
n = int(input())
for _ in range(n):
	l = int(input())
	s = input()
	print(moves(s))


x = int(input())
while x > 0:
	x -= 1
	i = input()
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(int(len(s) / 2))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	count = 0
	istrue = True
	while istrue == True:
		if '()' in s:
			ind = s.find('()')
			s = s[:ind] + s[ind + 2:]
			count += 1
		else:
			istrue = False
			print(n // 2 - count)


t = int(input())

def primes(n):
	count = 0
	rl = 0
	while n % 2 == 0:
		n = n // 2
		count += 1
	while n % 3 == 0:
		n = n // 3
		rl += 1
	if n != 1 or count > rl:
		return -1
	else:
		return [rl, count]
from math import *
for xy in range(t):
	n = int(input())
	pq = input()
	l = []
	cq = 0
	for xy in range(n):
		if len(l) > 0 and pq[xy] == ')' and (l[-1] == '('):
			l.pop()
		elif pq[xy] == '(':
			l.append('(')
		else:
			cq += 1
	print(cq)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(cnt, mn) = (0, 0)
	for x in s:
		if x == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < mn:
			mn = cnt
	print(max(0, -mn))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	f = 0
	t = 0
	for i in range(n):
		if s[i] == '(':
			f += 1
		else:
			f -= 1
		if f < 0:
			t += 1
			f = 0
	print(t)


for u in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	out = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
			if c < 0:
				c = 0
				out += 1
	print(out)


t = int(input())
for q in range(t):
	n = int(input())
	s = input()
	ans = 0
	(o, c) = (0, 0)
	for i in range(n):
		if s[i] == ')':
			if o > c:
				c += 1
			else:
				ans += 1
		else:
			o += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	brackets = input()
	q = []
	count = 0
	for j in range(n - 1, -1, -1):
		if brackets[j] == '(' and (not q):
			count += 1
		elif brackets[j] == '(' and q:
			v = q.pop()
		else:
			q.append(brackets[j])
	print(count)


t = int(input())
for p in range(0, t):
	n = int(input())
	s = input()
	count = 0
	k = 0
	for i in range(n - 1, -1, -1):
		if s[i] == '(':
			count += 1
		elif s[i] == ')':
			count -= 1
		if count >= 1:
			k += 1
			count = 0
	print(k)


for _ in range(int(input())):
	N = int(input())
	string = input()
	stack = []
	for s in string:
		if not stack:
			stack.append(s)
		elif stack[-1] == '(' and s == ')':
			stack.pop()
		else:
			stack.append(s)
	print(len(stack) // 2)


for T in range(int(input())):
	n = int(input())
	string = input()
	stack = []
	count = 0
	for i in range(n):
		if len(stack) > 0:
			if stack[-1] == '(' and string[i] == ')':
				count += 1
				stack = stack[:len(stack) - 1]
			else:
				stack.append(string[i])
		else:
			stack.append(string[i])
	print((n - 2 * count) // 2)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	x = input()
	c = 0
	m = 0
	for i in x:
		if i == '(':
			c += 1
		elif c <= 0:
			m += 1
		else:
			c -= 1
	print(m)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(p, ans) = (0, 0)
	for c in s:
		if c == '(':
			p += 1
		else:
			p -= 1
		if p < 0:
			ans = min(ans, p)
	print(abs(ans))


import getopt
import sys
import math
onlyCase = -1
verbose = False
try:
	(opts, args) = getopt.getopt(sys.argv[1:], 'vc:', ['case='])
except getopt.GetoptError as err:
	print(str(err))
	sys.exit(2)
for (o, a) in opts:
	if o in ('-c', '--case'):
		onlyCase = int(a)
	elif o == '-v':
		verbose = True
	else:
		sys.exit()
ncases = int(input())
for c in range(1, ncases + 1):
	_ = int(input())
	brackets = list(input())
	if onlyCase != -1 and onlyCase != c:
		continue
	if verbose:
		print(brackets)
	tofix = 0
	opened = 0
	closed = 0
	for b in brackets:
		if b == '(':
			opened += 1
		elif b == ')':
			closed += 1
		else:
			print('Bah')
		if closed - opened > tofix:
			tofix = closed - opened
	print('%d' % tofix)


for i in range(int(input())):
	n = int(input())
	st = input()
	string = list(st)
	c = 0
	while c < len(string) - 1:
		if c < len(string) and string[c] == '(' and (string[c + 1] == ')'):
			string.pop(c)
			string.pop(c)
			c = 0
		else:
			c += 1
	print(len(string) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	for i in range(n):
		if len(stack) != 0:
			if stack[-1] == '(':
				if s[i] == ')':
					stack.pop()
				else:
					stack.append(s[i])
			else:
				stack.append(s[i])
		else:
			stack.append(s[i])
	ans = len(stack) // 2
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = input()
	ans = 0
	ss = 0
	i = 0
	while i < n:
		x = 0
		while i < n and a[i] == '(':
			i += 1
			x += 1
		while i < n and a[i] == ')':
			i += 1
			x -= 1
		if x > 0:
			ss += x
		elif x < 0:
			if ss + x < 0:
				ans += abs(ss + x)
				ss = 0
			else:
				ss = ss + x
	print(ss)


for t in range(int(input())):
	n = int(input())
	s = input()
	stack = [0 for i in range(n)]
	i = -1
	for item in s:
		if item == '(':
			i += 1
			stack[i] = '('
		elif item == ')' and stack[i] == '(':
			i -= 1
		else:
			i += 1
			stack[i] = ')'
	print((i + 1) // 2)


test_case_num = int(input())
for i in range(test_case_num):
	num_moves = []
	counter = 0
	n = int(input())
	s = input()
	for elements in s:
		if elements == ')':
			counter += 1
		else:
			counter -= 1
		num_moves.append(counter)
	if max(num_moves) > 0:
		print(max(num_moves))
	else:
		print(0)


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count = 0
	stack = deque([])
	for i in s:
		if i == '(':
			stack.append(i)
		elif stack:
			stack.pop()
	while stack:
		count += 1
		stack.pop()
	print(count)


T = int(input())
for _ in range(T):
	n = int(input())
	s = input()
	close = 0
	opens = 0
	count = 0
	for i in range(n):
		if s[i] == ')':
			close += 1
			if close > opens:
				count += 1
				close = 0
				opens = 0
		if s[i] == '(':
			opens += 1
	print(count)


def make_reg(s):
	close = open = wrong = 0
	for (i, c) in enumerate(s):
		if c == ')':
			close += 1
		else:
			open += 1
		if close > open:
			wrong += 1
			close -= 1
	return wrong
num = int(input())
res = []
for i in range(num):
	input()
	s = input()
	res.append(make_reg(s))
for r in res:
	print(r)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	b = [0]
	for i in range(n):
		if s[i] == '(':
			b.append(b[-1] + 1)
		elif s[i] == ')':
			b.append(b[-1] - 1)
	print(-min(b))


_MULTITEST = True

def solve():
	n = int(input())
	s = str(input())
	sumBracket = 0
	dif = 0
	for i in range(n):
		sumBracket += 1 if s[i] == '(' else -1
		dif = min(dif, sumBracket)
	print(abs(dif))
t = int(input()) if _MULTITEST else 1
for tt in range(t):
	solve()


t = int(input())
while t:
	n = int(input())
	s = input()
	s = list(s)
	while 1:
		f = 0
		i = 0
		while i < len(s) - 1:
			if s[i] == '(' and s[i + 1] == ')':
				s.pop(i)
				s.pop(i)
				f = 1
				break
			i += 1
		if f == 0:
			break
	print(len(s) // 2)
	t -= 1


tea = int(input())
for _ in range(tea):
	en = int(input())
	yes = input()
	ai = 0
	el = 0
	are = 0
	see = 0
	while ai < en:
		if yes[ai] == '(':
			el += 1
		else:
			are += 1
		if el < are:
			if yes[ai] == ')':
				see += 1
				yes = yes[:ai] + yes[ai + 1:] + ')'
				are -= 1
		else:
			ai += 1
	print(see)


import math
import bisect
import sys
from collections import OrderedDict
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
T = inp()
for t in range(T):
	N = inp()
	S = insr()
	l = 0
	r = 0
	out = 0
	for i in range(N):
		if S[i] == ')':
			l += 1
		else:
			r += 1
		if l > r:
			out += 1
			l -= 1
	print(out)


for i in range(int(input())):
	n = int(input())
	s = input()
	st = 0
	fans = 0
	for j in s:
		if j == ')':
			st -= 1
		else:
			st += 1
		if st < 0:
			fans += 1
			st = 0
	print(fans)


for tc in range(int(input())):
	n = int(input())
	string = input()
	num_prev = 0
	num_next = 0
	baskets = []
	result = 0
	for i in range(n):
		if string[i] == '(':
			baskets.append(True)
		elif len(baskets) and baskets[-1]:
			baskets.pop(-1)
		else:
			result += 1
	print(result)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt1 = 0
	cnt2 = 0
	bal = 0
	for i in range(n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			bal += 1
			cnt1 += 1
	print(cnt1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt = 0
	opens = 0
	for i in range(n):
		if s[i] == ')':
			if opens == 0:
				cnt += 1
			else:
				opens -= 1
		else:
			opens += 1
	print(cnt)


t = int(input())
for p in range(t):
	n = int(input())
	string = str(input())
	count = flag = miss = 0
	for i in range(n):
		if string[i] == '(':
			count += 1
		elif string[i] == ')':
			if count > 0:
				count -= 1
			else:
				miss += 1
	print(miss)


testcases = int(input())
for testcase in range(testcases):
	count = 0
	brack = 0
	nn = input()
	strs = input()
	for i in strs:
		if i == '(':
			brack += 1
			continue
		if i == ')' and brack == 0:
			count += 1
		else:
			brack -= 1
	print(count)


(z, zz) = (input, lambda : list(map(int, z().split())))
mod = 10 ** 9 + 7
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0:
			return 0
	return 1
n = int(z())
for _ in range(n):
	z()
	l = z()
	t = 0
	c = 0
	for i in l:
		if i == '(':
			t += 1
			continue
		t -= 1
		if t < 0:
			c += 1
			t = 0
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	m = 0
	count = 0
	for i in range(n):
		if s[i] == '(':
			count += 1
		elif s[i] == ')':
			count -= 1
			m = min(m, count)
	print(abs(m))


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = []
	count = 0
	for i in range(n):
		if s[i] == '(':
			l.append(s[i])
		elif len(l) != 0:
			l.pop()
		else:
			count += 1
	print(count)


for i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	for i in s:
		if i == '(':
			ans += 1
		elif ans != 0:
			ans -= 1
	print(ans)


t = int(input())
for i in range(t):
	len_ = int(input())
	chars = [i for i in input()]
	o = 0
	c = 0
	val = 0
	for j in chars:
		if j == '(':
			o += 1
		elif j == ')' and o > c:
			c += 1
	print(o - c)


def fun(st):
	ob = 0
	cb = 0
	for i in st:
		if i == ')':
			if ob > 0:
				ob -= 1
			else:
				cb += 1
		else:
			ob += 1
	print((cb + ob) // 2)
T = int(input())
for _ in range(T):
	n = int(input())
	st = input()
	fun(st)


t = int(input())
while t:
	size = int(input())
	bracks = list(map(str, input()))
	conso = 0
	consb = 0
	counter = 0
	for i in range(size):
		if i < len(bracks):
			if bracks[i] == '(':
				if consb > conso:
					counter += abs(consb - conso)
					conso = 1
					consb = 0
					bracks.pop()
				else:
					conso += 1
		if i < len(bracks):
			if bracks[i] == ')':
				consb += 1
	print(counter)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	st = []
	count = 0
	c = 0
	for i in range(len(s)):
		if s[i] == '(':
			count += 1
			st.append(count)
		elif len(st) == 0:
			c += 1
		else:
			st.pop()
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	min_num = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < min_num:
			min_num = cnt
	print(-1 * min_num)


t = int(input())
for i in range(0, t):
	n = int(input())
	s = str(input())
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(ans, level) = (0, 0)
	for c in s:
		if c == '(':
			level += 1
		elif c == ')':
			level -= 1
		if level < 0:
			level = 0
			ans += 1
	print(ans)


t = int(input(''))
a = []

def go(s):
	st = 0
	fi = 0
for i in range(t):
	n = int(input())
	s = str(input())
	string = []
	for i in range(n):
		if s[i] == '(':
			string.append('(')
		if s[i] == ')':
			string.append(')')
	st = 0
	ans = 0
	i = 0
	while i < n:
		if string[i] == '(':
			st += 1
		if string[i] == ')':
			if st == 0:
				for j in range(i, n - 1):
					string[j] = string[j + 1]
				string[n - 1] = ')'
				ans += 1
				i -= 1
			else:
				st -= 1
		i += 1
	a.append(ans)
for i in range(t):
	print(a[i])


for _ in range(int(input())):
	x = int(input())
	arr = list(input())
	op = 0
	cl = 0
	ans = 0
	for i in range(x):
		if arr[i] == '(':
			op += 1
		if arr[i] == ')':
			cl += 1
			if cl > op:
				cl -= 1
				ans += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	opens = 0
	closed = 0
	cnt = 0
	for i in s:
		if i == ')':
			if opens == 0:
				cnt += 1
			else:
				opens -= 1
		elif i == '(':
			opens += 1
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	co = 0
	cc = 0
	c = 0
	for i in s:
		if i == '(':
			co += 1
		else:
			cc += 1
		if cc > co:
			cc -= 1
			c += 1
	print(c)


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	(op, cl) = [0] * 2
	for i in range(n):
		if s[i] == '(':
			op += 1
		else:
			cl += 1
			if op > 0:
				op -= 1
				cl -= 1
	print(op)


t = int(input())
for _ in range(t):
	n = int(input())
	st = list(input().rstrip('\n'))
	count1 = 0
	for each in st:
		if each == '(':
			count1 += 1
		if each == ')':
			if count1 > 0:
				count1 -= 1
	print(count1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	ans = 0
	c = 0
	for i in s:
		if i == '(':
			c -= 1
		else:
			c += 1
		ans = max(ans, c)
	s.reverse()
	c = 0
	for i in s:
		if i == ')':
			c -= 1
		else:
			c += 1
		ans = max(ans, c)
	print(ans)


t = int(input())
for s in range(t):
	n = int(input())
	string = input()
	count = 0
	add = 0
	for i in string:
		if i == '(':
			add += 1
		else:
			add -= 1
		if add < 0:
			count += 1
			add = 0
	print(count)


for _ in range(int(input())):
	n = int(input())
	l = input()
	while True:
		if '()' in l:
			j = l.index('()')
			l = l[:j] + l[j + 2:]
		else:
			print(len(l) // 2)
			break


from sys import *
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	sir = stdin.readline()
	nr0 = 0
	nr1 = 0
	for ch in sir:
		if ch == '(':
			nr0 += 1
		elif ch == ')':
			if nr0 != 0:
				nr0 -= 1
			else:
				nr1 += 1
	stdout.write(str(nr0) + '\n')


for _ in range(int(input())):
	n = int(input())
	s = input()
	p = []
	for ch in s:
		p.append(ch)
	s = p
	for i in range(n):
		if s[i] == '(':
			for j in range(i + 1, n):
				if s[j] == ')':
					s[i] = 0
					s[j] = 0
					break
	c = 0
	for ch in s:
		if ch != 0:
			c += 1
	print(c // 2)


for _ in range(int(input())):
	input()
	s = input()
	res = 0
	c = 0
	for v in s:
		if v == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			res += 1
			c += 1
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	a = 0
	b = 0
	for i in range(n):
		if s[i] == ')':
			b += 1
		else:
			a += 1
		if b > a:
			cnt += 1
			b -= 1
		else:
			a -= b
			b = 0
	print(cnt)


num = int(input())
ans = []
for i in range(num):
	lenn = int(input())
	seq = [x for x in input()]
	for j in range(lenn):
		if seq[j] == '(':
			point = j
			for k in range(point, lenn):
				if seq[k] == ')':
					seq[point] = '0'
					seq[k] = '0'
					break
	anss = 0
	for t in range(lenn):
		if seq[t] == '0':
			anss += 1
	ans.append(lenn - anss)
for i in range(num):
	print(int(ans[i] / 2))


from math import *
from copy import *
from heapq import *
from string import *
from random import *
from bisect import *
from sys import stdin
from sys import maxsize
from operator import *
from itertools import *
from decimal import Decimal
from collections import Counter
from collections import defaultdict

def solve(s):
	n = len(s)
	st = []
	ans = 0
	for i in s:
		if i == '(':
			st.append(i)
		elif not st:
			ans += 1
		else:
			st.pop()
	return min(ans, len(st))
T = int(input())
for _ in range(T):
	N = int(stdin.readline())
	l = input()
	print(solve(l))


for i in range(int(input())):
	n = int(input())
	s = input()
	k = 0
	now = 0
	for i in range(n):
		if s[i] == '(':
			k += 1
		else:
			k -= 1
		now = min(now, k)
	print(-now)


from math import *
sInt = lambda : int(input())
mInt = lambda : map(int, input().split())
lInt = lambda : list(map(int, input().split()))
t = sInt()
for _ in range(t):
	n = sInt()
	s = input()
	s = list(s)
	ans = 0
	f = 0
	b = 0
	for i in s:
		if i == '(':
			f += 1
		else:
			b += 1
			if b > f:
				ans += 1
				b -= 1
	print(ans)


for t in range(int(input())):
	(openb, ans) = (0, 0)
	n = int(input())
	s = input()
	for i in range(n):
		if s[i] == '(':
			openb += 1
		else:
			openb -= 1
			if openb < 0:
				ans = max(ans, abs(openb))
	print(ans)


t = int(input())
for test in range(t):
	n = int(input())
	seq = list(input())
	(ans, k) = (0, 0)
	for br in seq:
		if br == '(':
			ans += 1
		elif ans > 0:
			ans -= 1
		else:
			k += 1
	print(k)


for _ in range(int(input())):
	(n, a, c, d) = (int(input()), list(str(input())), 0, [])
	for i in range(len(a)):
		c = c + 1 if a[i] == ')' else c - 1
		d.append(c)
	print(max(d))


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def solve(string_brackets):
	lb = list((ch for ch in string_brackets))
	open_b = '('
	opened = 0
	idx = 0
	swaps = 0
	while idx < len(string_brackets):
		if lb[idx] == open_b:
			opened += 1
		elif opened:
			opened -= 1
		else:
			swaps += 1
		idx += 1
	return swaps
iters = int(input())
for i in range(iters):
	_ = input()
	s = input()
	print(solve(s))


for _ in range(int(input())):
	n = int(input())
	s = input()
	br = 0
	ans = 0
	cl = 0
	for i in s:
		if i == '(':
			br += 1
		else:
			br -= 1
		if br < 0:
			br = 0
			cl += 1
	print(cl)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	kol = 0
	unp = 0
	for i in s:
		if i == ')' and kol == 0:
			unp += 1
		elif i == ')' and kol > 0:
			kol -= 1
		if i == '(':
			kol += 1
	print(unp)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	s = list(sys.stdin.readline().strip())
	stack = []
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif s[i] == ')':
			if len(stack) == 0:
				stack.append(')')
			elif stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
	res = 0
	for i in range(len(stack)):
		if stack[i] == ')':
			res += 1
	print(res)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = [0]
	for x in map(lambda o: -1 if o == ')' else 1, input()):
		arr.append(arr[-1] + x)
	print(-min(arr))


t = int(input())
nums = []
for i in range(t):
	n = int(input())
	nums.append(input())
output = []
for s in nums:
	counter = 0
	neg_counter = 0
	for s1 in s:
		if s1 == '(':
			counter += 1
		else:
			counter -= 1
			if counter < 0:
				neg_counter += 1
				counter = 0
	output.append(neg_counter)
for a in output:
	print(a)


t = int(input())
for _ in range(t):
	q = []
	n = int(input())
	s = input()
	size = 0
	for i in s:
		if i == '(':
			q.append(i)
			size += 1
		elif q and q[-1] == '(':
			q.pop()
			size -= 1
		else:
			q.append(i)
			size += 1
	print(size // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	for i in s:
		if st and i == ')' and (st[-1] == '('):
			st.pop(-1)
		else:
			st.append(i)
	print(len(st) // 2)


t = int(input())
for i in range(t):
	count = 0
	balance = 0
	n = int(input())
	s = list(input())
	for j in range(n - 1):
		if s[j] == '(':
			balance += 1
		elif s[j] == ')':
			balance -= 1
		if balance <= -1:
			for i in range(n - 1, j, -1):
				if s[i] == '(':
					count += 1
					balance += 1
					s[i] = ' '
					break
	print(count)


for i in range(int(input())):
	n = int(input())
	l = list(input())
	i = 0
	while i < len(l) - 1:
		if l[i] == '(' and l[i + 1] == ')':
			l.pop(i)
			l.pop(i)
			if i != 0:
				i = i - 1
		else:
			i = i + 1
	print(int(len(l) / 2))


def main():
	t = int(input())
	while t:
		n = input()
		s = input()
		lopen = 0
		for i in s:
			if i == '(':
				lopen += 1
			elif lopen:
				lopen -= 1
		print(lopen)
		t -= 1
main()


t = int(input())
for tt in range(t):
	n = int(input())
	a = input()
	a = list(a)
	count = 0
	sum = 0
	for i in a:
		if i == ')':
			if sum == 0:
				a.append(i)
				count = count + 1
			else:
				sum = sum - 1
		if i == '(':
			sum = sum + 1
	print(count)


import sys
from os import path
if path.exists('C:/Users/prana/Desktop/sublime/input.txt'):
	sys.stdin = open('C:/Users/prana/Desktop/sublime/input.txt', 'r')
	sys.stdout = open('C:/Users/prana/Desktop/sublime/output.txt', 'w')

def solve():
	n = int(input())
	s = list(input())
	temp = n // 2
	l = 0
	d = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			d += 1
		else:
			d -= 1
			if d < 0:
				d = 0
				ans += 1
	print(ans)
T = 1
T = int(input())
for _ in range(1, T + 1):
	print('Case #', _, file=sys.stderr)
	solve()


t = int(input())
ans = ''
for j in range(t):
	n = int(input())
	s = input()
	k = 0
	for i in range(n):
		if s[i] == '(':
			k += 1
		elif k > 0 and s[i] == ')':
			k -= 1
	ans += str(k) + '\n'
print(ans)


import sys
import math
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int, strInp()))
for t in range(int(input())):
	n = int(input())
	s = input()
	open = 0
	closeForOpen = 0
	for i in range(n):
		if s[i] == '(':
			open += 1
		if open > 0 and s[i] == ')':
			closeForOpen += 1
			open -= 1
	print((n - closeForOpen * 2) // 2)


t = int(input())
for caseNr in range(1, t + 1):
	n = int(input())
	brackets = str(input())
	i = 0
	left = 0
	right = 0
	moves = 0
	while i < len(brackets):
		if brackets[i] == '(':
			left += 1
		else:
			right += 1
		if right > left:
			moves += 1
			right -= 1
		i += 1
	print(moves)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	cnt = 0
	move = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			move += 1
			cnt = 0
	print(move)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cntl = 0
	cntr = 0
	for i in s:
		if i == '(':
			cntl += 1
		elif cntl == 0:
			cntr += 1
		else:
			cntl -= 1
	print(cntr)


import sys
import collections
input = sys.stdin.buffer.readline

def iinp() -> int:
	return int(input())

def linp() -> list:
	return [int(p) for p in input().split()]

def sinp():
	return input().decode('unicode_escape')
M = int(1000000000.0 + 7)
for _ in range(iinp()):
	n = iinp()
	s = sinp()
	sums = 0
	ans = 0
	for i in range(0, n):
		if s[i] == '(':
			sums -= 1
		else:
			sums += 1
		ans = max(ans, sums)
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	forwards = 0
	backards = 0
	operations = 0
	i = 0
	while i < n:
		if s[i] == '(':
			forwards = forwards + 1
			i = i + 1
		elif forwards > 0:
			forwards = forwards - 1
			i = i + 1
		else:
			s = s[:i] + s[i + 1:] + s[i]
			operations = operations + 1
	print(operations)


def Rev(x):
	if x == '(':
		return ')'
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	st = []
	for c in s:
		if st and Rev(st[-1]) == c:
			st.pop()
		else:
			st.append(c)
	ans += [len(st) // 2]
print(*ans, sep='\n')


def f(s):
	oc = 0
	for char in s:
		if char == '(':
			oc += 1
		elif oc > 0:
			oc -= 1
	return oc

def main():
	t = int(input())
	while t > 0:
		n = int(input())
		print(f(list(input())))
		t -= 1
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	j = 0
	state = answer = 0
	for j in s:
		if j == '(':
			state += 1
		else:
			state -= 1
			if state < 0:
				answer += 1
				state = 0
	print(answer)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	d = 0
	out = 0
	for c in s:
		if c == '(':
			d += 1
		elif d > 0:
			d -= 1
		else:
			out += 1
	print(out)


import math as m
for _ in range(int(input())):
	n = int(input())
	s = input()
	a = []
	for i in s:
		if i == ')' and len(a) != 0 and (a[-1] == '('):
			a.pop()
		else:
			a.append(i)
	print(len(a) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	if '()' in s:
		while s.count('()') != 0:
			s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	l = []
	for i in s:
		if i == '(':
			l.append(1)
		else:
			l.append(-1)
	val = 0
	key = 1
	mi = 0
	for j in l:
		val += j
		if val < 0:
			mi = min(val, mi)
	print(-1 * mi)


for _ in range(int(input())):
	n = int(input())
	seq = input()
	op = '('
	cl = ')'
	cou_op = 0
	cou_cl = 0
	chan = 0
	for i in range(n):
		if seq[i] == op:
			cou_op += 1
			if cou_cl > 0:
				cou_cl -= 1
			elif i != 0 and cou_cl != 0:
				chan += 1
		elif seq[i] == cl:
			cou_cl += 1
			if cou_op > 0:
				cou_op -= 1
			else:
				chan += 1
	print(chan)


def codeforces_round():
	for i in range(int(input())):
		x = int(input())
		y = input()
		stack = []
		incomplete = []
		for i in y:
			if i == '(':
				stack.append(i)
			elif stack:
				if stack.pop() != '(':
					incomplete.append(i)
			else:
				incomplete.append(i)
		print(len(incomplete))
codeforces_round()


from sys import stdin, stdout

def main():
	t = int(stdin.readline())
	for case in range(t):
		n = int(stdin.readline())
		s = stdin.readline()
		(left, right) = (0, 0)
		move = 0
		for i in range(n):
			if s[i] == '(':
				left += 1
			else:
				right += 1
				if left < right:
					move += 1
					right -= 1
		stdout.write(str(move))
		stdout.write('\n')
	return
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	second = 0
	first = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			second += 1
			if second > first + ans:
				ans += 1
		else:
			first += 1
	print(ans)


t = int(input())
s = ''
l = []
o = []
c = []
count = 0
prev = 0
stack = []
for i in range(t):
	n = int(input())
	s = input()
	l.append(s)
for i in l:
	for j in range(len(i) - 1):
		if i[j] == '(':
			count += 1
		elif i[j] == ')':
			count -= 1
		if count < prev:
			prev = count
	stack.append(prev)
	count = 0
	prev = 0
for i in stack:
	print(-i)


import sys
input = sys.stdin.readline
for T in range(int(input())):
	n = int(input().strip())
	s = input().strip()
	stk = []
	cnt = 0
	stk.append(s[0])
	for i in range(1, n):
		if len(stk) > 0 and s[i] == ')' and (stk[-1] == '('):
			stk.pop()
		else:
			stk.append(s[i])
	print(len(stk) // 2)


def solve(string):
	while string.find('()') != -1:
		string = string.replace('()', '')
	return len(string) // 2
N = int(input())
for i in range(N):
	L = input()
	string = input()
	print(solve(string))


def main():
	testCases = int(input())
	for tests in range(testCases):
		n = int(input())
		stack = []
		demoString = input()
		index = 0
		count = 0
		for index in range(n):
			if demoString[index] == '(':
				stack.append('(')
			elif demoString[index] == ')' and len(stack) == 0:
				count = count + 1
			elif demoString[index] == ')' and stack.pop() == '(':
				pass
		print(count)
main()


for _ in range(int(input())):
	n = int(input())
	arr = str(input())
	ans = []
	count = 0
	for i in arr:
		if i == '(':
			ans.append(i)
		if len(ans) == 0 and i == '(':
			ans.append(i)
		elif len(ans) == 0 and i == ')':
			count += 1
		elif ans[-1] == '(' and i == ')':
			ans.pop()
	if count == 0:
		print(0)
	else:
		print(count)


def process():
	n = int(input())
	a = input().strip()
	q = 0
	k = 0
	for c in a:
		if c == '(':
			q += 1
		elif c == ')':
			if q > 0:
				q -= 1
			else:
				k += 1
	print(k)
t = int(input())
for _ in range(t):
	process()


t = int(input())
for _ in range(t):
	s = int(input())
	s = input()
	ans = 0
	for z in s:
		if z == '(':
			ans += 1
		elif z == ')' and ans > 0:
			ans -= 1
	print(ans)


for t in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	l = []
	for i in s:
		if i == '(':
			l.append(i)
		elif i == ')' and len(l) > 0:
			l.pop()
		else:
			ans += 1
	print(ans)


t = int(input())
while t:
	n = int(input())
	a = input()
	s = []
	(l, r) = (0, 0)
	for i in a:
		if s == [] and i == '(':
			s.append(i)
		elif s == [] and i == ')':
			l += 1
		elif s[-1] == '(' and i == '(':
			s.append('(')
		elif s[-1] == '(' and i == ')':
			s.pop()
	if len(s) == l:
		print(l)
	t -= 1


t = int(input())
for i in range(t):
	n = int(input())
	bracks = input()
	L = 0
	R = 0
	ans = 0
	for x in range(n):
		if bracks[x] == ')':
			L = L + 1
		else:
			R = R + 1
		if L > R:
			ans = ans + 1
			L = 0
			R = 0
	print(ans)


def solve():
	n = int(input())
	s = input()
	answer = 0
	counter = 0
	while len(s) > 0:
		remain = ''
		for c in list(s):
			if c == '(':
				counter += 1
			elif counter > 0:
				counter -= 1
			else:
				remain += ')'
				answer += 1
		s = remain
	print(answer)
num_test = int(input())
for _ in range(num_test):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	not_arranged = []
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif s[i] == ')':
			if len(stack) == 0:
				not_arranged.append(')')
			elif stack[-1] == '(':
				stack.pop()
	print(len(stack))


t = int(input())
for _ in range(0, t):
	n = int(input())
	a = input()
	a = list(a)
	flag = 0
	while 1:
		flag = 0
		for i in range(0, len(a) - 1):
			if a[i] == '(' and a[i + 1] == ')':
				a.pop(i)
				a.pop(i)
				flag = 1
				break
		if flag == 0:
			break
	p = a.count('(')
	print(p)


t = int(input())
for test in range(t):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		elif c == 0:
			ans += 1
		else:
			c -= 1
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = input()
	b = []
	count = 0
	for i in range(n):
		if a[i] == ')' and len(b) == 0:
			count += 1
			b.append(')')
		elif a[i] == '(' and len(b) == 0:
			b.append('(')
		elif a[i] == '(' and b[-1] == '(' or (a[i] == ')' and b[-1] == ')'):
			b.append(a[i])
		elif a[i] == '(' and b[-1] == ')':
			b.append(a[i])
		elif a[i] == ')' and b[-1] == '(':
			b.pop()
	if len(b):
		count += (len(b) - 1) // 2
	print(count)


t = int(input())

def calc():
	count = 0
	input()
	l = list(input())
	while True:
		a = l.index('(')
		b = l.index(')')
		if a < b:
			l.remove('(')
			l.remove(')')
		else:
			l.pop(len(l) - l[::-1].index('(') - 1)
			l.remove(')')
			count = count + 1
		if len(l) == 0:
			break
	print(count)
for _ in range(0, t):
	calc()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	a = []
	c = 0
	for i in s:
		if i == '(':
			a.append(')')
		elif len(a) == 0:
			c += 1
		elif a[-1] == ')':
			a.remove(i)
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	bal = 0
	minbal = 0
	for i in range(n):
		if s[i] == ')':
			bal -= 1
		else:
			bal += 1
		minbal = min(minbal, bal)
	print(-minbal)


def wa(s):
	return s.replace('()', '')

def ans(s):
	k = s.count('()')
	if k == len(s) // 2:
		print(0)
	else:
		while k > 0:
			k = s.count('()')
			s = wa(s)
			if k == 0:
				break
		print(len(s) // 2)
t = int(input())
while t > 0:
	a = int(input())
	s = str(input())
	ans(s)
	t -= 1


def help():
	n = int(input(' '))
	stri = input()
	stack = []
	leng = 0
	for i in range(n):
		if leng > 0:
			if stack[leng - 1] == '(' and stri[i] == ')':
				stack.pop()
				leng -= 1
			else:
				stack.append(stri[i])
				leng += 1
		else:
			stack.append(stri[i])
			leng += 1
	print(leng // 2)
for _ in range(int(input())):
	help()


for _ in range(int(input())):
	n = int(input())
	a = input()
	ct1 = 0
	ct0 = 0
	count = 0
	for i in a:
		if i == '(':
			ct1 += 1
		elif i == ')':
			ct0 += 1
		if ct0 > ct1:
			count += 1
			ct0 = ct0 - 1
	print(count)


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
t = fi()
while t > 0:
	t -= 1
	n = fi()
	s = si()
	o = c = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			o += 1
		else:
			c += 1
		if c > o:
			ans += 1
			c -= 1
	print(ans)


def solve(n, brackets):
	bc = 0
	totalmoves = 0
	for i in range(0, n):
		bc += 1 if brackets[i] == '(' else -1
		if bc < 0:
			totalmoves += 1
			bc = 0
	return totalmoves
t = int(input())
results = list()
for _ in range(0, t):
	n = int(input())
	brackets = input()
	results.append(solve(n, brackets))
for result in results:
	print(result)


n = int(input())
for i in range(n):
	t = int(input())
	s = input()
	o = 0
	r = 0
	for i in s:
		if i == ')':
			o -= 1
			if o < 0:
				r += 1
				o = 0
		else:
			o += 1
	print(r)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	req = 0
	cur = 0
	for i in range(len(s)):
		if s[i] == '(':
			cur += 1
		elif s[i] == ')' and cur == 0:
			req += 1
		else:
			cur -= 1
	print(req)


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10 ** 9 + 7
spf = [i for i in range(MAXN)]
spf[0] = spf[1] = -1

def sieve():
	for i in range(2, MAXN, 2):
		spf[i] = 2
	for i in range(3, int(MAXN ** 0.5) + 1):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def fib(n, m):
	if n == 0:
		return [0, 1]
	else:
		(a, b) = fib(n // 2)
		c = a % m * (b % m * 2 - a % m) % m
		d = a % m * (a % m) % m + b % m * b % m % m
		if n % 2 == 0:
			return [c, d]
		else:
			return [d, c + d]

def charIN(x=' '):
	return sys.stdin.readline().strip().split(x)

def arrIN(x=' '):
	return list(map(int, sys.stdin.readline().strip().split(x)))

def ncr(n, r):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % MOD
		den = den * (i + 1) % MOD
	return num * pow(den, MOD - 2, MOD) % MOD

def flush():
	return sys.stdout.flush()
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	ans = 0
	for i in range(n):
		if s[i] == '(':
			st.append('(')
		elif st:
			st.pop()
		else:
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	str1 = input()
	s1 = []
	for i in str1:
		if i == '(':
			s1.append(i)
		elif len(s1) != 0 and s1[-1] == '(':
			s1.pop()
	print(len(s1))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(ans, cnt) = (0, 0)
	for x in s:
		if x == '(':
			cnt += 1
		else:
			cnt -= 1
			if cnt < 0:
				cnt = 0
				ans += 1
	print(ans)


n = int(input())
for i in range(n):
	x = int(input())
	s = list(input())
	stack = []
	c = 0
	for i in range(x):
		if s[i] == '(':
			stack.append(s[i])
		elif stack == []:
			c += 1
		elif stack[-1] == '(':
			stack.pop()
		else:
			c += 1
	print(c)


a = input()
for x in range(int(a)):
	b = input()
	c = input()
	list1 = []
	for i in c:
		if len(list1) == 0:
			list1.append(i)
		elif list1[-1] == '(' and i == ')':
			list1.pop()
		else:
			list1.append(i)
	print(len(list1) // 2)


for i in range(int(input())):
	n = int(input())
	st = list(input())
	stc = []
	ct = 0
	for i in range(len(st)):
		if st[i] == '(':
			stc.append(st[i])
		elif stc:
			a = stc.pop()
			ct += 1
	ans = (n - 2 * ct) // 2
	print(ans)


for _ in range(int(input())):
	a = input()
	s = input()
	cc = 0
	c = 0
	for i in s:
		if i == ')':
			cc += 1
		else:
			cc -= 1
		if i == ')' and cc > 0:
			c += 1
			cc = 0
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	bracket = input()
	minBracket = 0
	curBracket = 0
	for elem in bracket:
		if elem == '(':
			curBracket += 1
		else:
			curBracket -= 1
		if minBracket > curBracket:
			minBracket = curBracket
	print(-minBracket)


t = int(input())
while t > 0:
	t -= 1
	leng = int(input())
	s = list(input())
	(l, r) = (0, 0)
	for brac in s:
		if brac == '(':
			l += 1
		elif brac == ')':
			if l > 0:
				l -= 1
			else:
				r += 1
	print(r)


def mb(arr, n):
	st = []
	for i in arr:
		if i == '(':
			st.append(i)
		elif len(st) != 0:
			st.pop()
	return len(st)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = input()
	print(mb(arr, n))
	print('')


t = int(input())
for k in range(0, t):
	unuse = int(input())
	st = str(input())
	n = list()
	for el in st:
		n.append(el)
	i = 0
	while i < len(n):
		if n[i] == '(':
			for j in range(i + 1, len(n)):
				if n[j] == ')':
					n.pop(i)
					n.pop(j - 1)
					i -= 1
					break
		i += 1
	print(int(len(n) / 2))


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	total = 0
	count1 = 0
	count2 = 0
	for s in string:
		if s == '(':
			count1 += 1
		if s == ')':
			count2 += 1
			if count2 > count1:
				total += 1
				count2 -= 1
	print(total)


for _ in range(int(input())):
	n = int(input())
	s = input()
	d = ''
	no_open = 0
	c = 0
	i = 0
	while len(d) != n:
		if s[i] == ')':
			if no_open == 0:
				c = c + 1
				d = d + ')'
			else:
				d = d + ')'
				no_open -= 1
		else:
			d = d + '('
			no_open += 1
		i = i + 1
	print(c)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	closeB = 0
	openB = 0
	for ch in s:
		if ch == '(':
			openB += 1
		else:
			closeB += 1
			if openB >= 1:
				openB -= 1
				closeB -= 1
	print(closeB)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	b = 0
	c = n
	for i in s:
		if i == '(':
			b += 1
		else:
			b -= 1
		c = min(b, c)
	print(abs(min(0, c)))


for t in range(int(input())):
	n = int(input())
	s = input()
	s = list(s)
	o = 0
	c = 0
	an = 0
	for i in s:
		if i == '(':
			o = o + 1
		if i == ')':
			c = c + 1
		if c > o:
			an = max(an, c - o)
	print(an)


def solve(n):
	m = 0
	c = 0
	for i in n:
		if ')' == i:
			c = c - 1
		else:
			c = c + 1
		m = min(c, m)
	return m * -1
t = int(input())
for i in range(t):
	x = int(input())
	n = input()
	print(solve(n))


t = int(input())
c = []
for i in range(t):
	n = int(input())
	a = input()
	ans = 0
	k = 0
	for j in a:
		if j == '(':
			ans += 1
		else:
			ans -= 1
		if ans < 0:
			k += abs(ans)
			ans = 0
	c.append(k)
for j in c:
	print(j)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	c = 0
	d = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			c += 1
		elif s[i] == ')':
			if c <= d:
				ans += 1
			else:
				d += 1
	print(ans)


t = int(input())
br = []

def quantity(n: int, brackets: str):
	while brackets.find('()') != -1:
		brackets = brackets[:brackets.find('()')] + brackets[brackets.find('()') + 2:]
	if brackets:
		return len(brackets) // 2
	return 0
for i in range(t):
	br.append(quantity(int(input()), input()))
for elem in br:
	print(elem)


try:

	def arrange(sg):
		count = 0
		stk = []
		for i in range(len(sg)):
			if sg[i] == '(':
				stk.append(sg[i])
			elif sg[i] == ')':
				if stk:
					stk.pop()
				else:
					count += 1
		return count
	k = int(input())
	for t in range(k):
		z = input()
		l = input()
		print(arrange(l))
except Exception:
	pass


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	ANS = 0
	for j in range(len(s)):
		if s[j] == '(':
			c += 1
		elif s[j] == ')':
			c -= 1
		if c < 0:
			ANS += 1
			c = 0
	print(ANS)


import sys
from sys import stdin
from collections import deque
from math import factorial
from itertools import groupby

def neo():
	return map(int, input().split())

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = deque()
	for i in s:
		if i == '(':
			st.append(i)
		elif len(st) > 0:
			st.pop()
	print(len(st))


t = int(input())
for p in range(t):
	n = int(input())
	s = input()
	d = n // 2
	c = 0
	for i in s:
		if i == '(':
			c += 1
		elif c > 0:
			d -= 1
			c -= 1
	print(c)


n = int(input())
for i in range(n):
	n2 = int(input())
	s = input()
	opening = 0
	closing = 0
	minm = 0
	for item in s:
		if item == '(':
			opening += 1
			if max(0, closing - opening) > minm:
				minm = max(0, closing - opening)
		else:
			closing += 1
			current = max(0, closing - opening)
			if max(0, closing - opening) > minm:
				minm = max(0, closing - opening)
	print(minm)


for _ in range(int(input())):
	input()
	level = 0
	result = 0
	for c in input():
		if c == '(':
			level += 1
		else:
			level -= 1
			if level < 0:
				result += 1
				level += 1
	print(result)


import math
from collections import Counter, deque
L = lambda : list(map(int, input().split()))
M = lambda : map(int, input().split())
I = lambda : int(input())
IN = lambda : input()
mod = 10 ** 9 + 7

def s(a):
	print(' '.join(list(map(str, a))))

def solve():
	n = I()
	s = IN()
	o = 0
	a = 0
	for i in range(n):
		if s[i] == '(':
			o += 1
		elif o == 0:
			a += 1
		else:
			o -= 1
	print(a)
for i in range(I()):
	solve()


for test in range(int(input())):
	num = int(input())
	s = input()
	l = 0
	r = 0
	for c in s:
		if c == ')' and l > 0:
			l = l - 1
		elif c == '(':
			l = l + 1
		else:
			r = r + 1
	if l > r:
		print(l)
	else:
		print(r)


w = int(input())
for x in range(w):
	n = int(input())
	s = input()
	f = 0
	m = 0
	for x in range(n):
		if s[x] == '(':
			f += 1
		elif f > 0:
			f -= 1
		else:
			m += 1
	print(m)


for i in range(int(input())):
	n = int(input())
	a = input()
	cnt = 0
	min1 = 0
	for i in a:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			if min1 > cnt:
				min1 = cnt
	print(abs(min1))


t = int(input())
for t in range(t):
	p = int(input())
	s = input()
	a = 0
	for i in s:
		if i == '(':
			a += 1
		elif a > 0:
			a -= 1
	print(a)


for i in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	for ch in s:
		if ch == ')' and stack and (stack[-1] == '('):
			stack.pop()
		else:
			stack.append(ch)
	print(len(stack) // 2)


for t in range(int(input())):
	n = int(input())
	s = str(input()).strip()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
			top = i
			continue
		top = stack[-1]
		if i == ')' and top == '(':
			stack.pop()
		else:
			stack.append(i)
	print(int(len(stack) / 2))


for _ in range(int(input())):
	n = int(input())
	s = input()
	ctop = 0
	ctclose = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			ctop += 1
		else:
			ctclose += 1
		if ctclose > ctop:
			ctclose -= 1
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	sum = 0
	sum2 = 0
	for y in range(n):
		if s[y] == '(':
			sum = sum + 1
		elif sum > 0:
			sum = sum - 1
		else:
			sum2 = sum2 + 1
	print(sum2)


def ints():
	return list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	a = input()
	m = 0
	c = 0
	for i in range(n):
		if a[i] == '(':
			c += 1
		else:
			c -= 1
		m = min(m, c)
	no = 0
	c = 0
	for i in range(n)[::-1]:
		if a[i] == '(':
			c -= 1
		else:
			c += 1
		no = min(no, c)
	print(abs(max(m, no)))


import sys, math
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	a = int(input())
	s = input()
	mas = []
	for i in s:
		mas.append(i)
	f = 0
	ans = 0
	for i in range(a):
		i -= f
		if i < 0:
			i = 0
		if len(mas) != 0:
			if mas[i] == '(':
				for j in range(i, a - f):
					if mas[j] == ')':
						ans += 1
						del mas[i]
						del mas[j - 1]
						f += 2
						break
		else:
			break
	print((a - ans * 2) // 2)


t = int(input())
for _ in range(t):
	j = int(input())
	s = input()
	s = list(s)
	stack = []
	for i in s:
		if i == ')' and len(stack) == 0:
			continue
		elif i == ')' and len(stack) != 0:
			stack.pop()
		elif i == '(':
			stack.append('(')
	print(len(stack))


INT_MAX = 10 ** 30 + 7
MOD = 10 ** 9 + 7

def INPUT():
	return list((int(i) for i in input().split()))

def LIST_1D_ARRAY(n):
	return [0 for _ in range(n)]

def LIST_2D_ARRAY(m, n):
	return [[0 for _ in range(n)] for _ in range(m)]
for i in range(int(input())):
	n = int(input())
	s = input()
	A = [0] * n
	S = [0] * (n + 1)
	for i in range(n):
		if s[i] == '(':
			A[i] = 1
		else:
			A[i] = -1
	bool = True
	for i in range(1, n + 1):
		S[i] = S[i - 1] + A[i - 1]
		if S[i] < 0:
			bool = False
	if bool is False:
		ans = 0
		for i in range(n + 1):
			if S[i] < 0:
				ans = max(ans, abs(S[i]))
		print(ans)
	else:
		print(0)


t = int(input())
while t > 0:
	n = int(input())
	a = input()
	ans = float('inf')
	c = 0
	for i in range(len(a)):
		if a[i] == '(':
			c = c + 1
		else:
			c = c - 1
		ans = min(ans, c)
	print(-ans)
	t = t - 1


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
testcases = int(input())
for j in range(testcases):
	n = int(input())
	brackets = [k for k in input()]
	outoforder = 0
	prefl = []
	count1 = 0
	for s in range(n):
		if brackets[s] == '(':
			count1 += 1
		prefl.append(count1)
	sofar = 0
	for s in range(n):
		if brackets[s] == ')':
			sofar += 1
			if prefl[s] >= sofar:
				continue
			else:
				sofar -= 1
				outoforder += 1
	print(outoforder)


from collections import Counter, defaultdict, deque
import sys
input = sys.stdin.readline

def primes(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return factors

def solve():
	n = int(input())
	s = input().strip()
	cur = 0
	ans = 0
	for i in s:
		if i == '(':
			cur += 1
		elif cur:
			cur -= 1
		else:
			ans += 1
	print(ans)
tt = int(input())
for test in range(tt):
	solve()


import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	s = input()
	ar = list()
	v = 0
	for i in range(n):
		if len(ar) == 0:
			ar.append(s[i])
		elif ar[-1] == '(' and s[i] == ')':
			ar.pop()
		else:
			ar.append(s[i])
	print(len(ar) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	bracket = input()
	opening_stack = []
	open = ['(']
	count = 0
	for i in bracket:
		if i == open[0]:
			opening_stack.append(i)
		elif len(opening_stack) == 0:
			count += 1
		else:
			opening_stack.pop()
	print(count)


n = int(input())
for i in range(n):
	m = int(input())
	s = str(input())
	c = 0
	sum = 0
	for j in range(0, len(s)):
		if s[j] == '(':
			c = c + 1
		elif s[j] == ')' and c == 0:
			sum = sum + 1
		elif s[j] == ')':
			c = c - 1
	print(sum)


t = int(input())
ar = []
for i in range(t):
	n = int(input())
	s1 = input()
	s = list(s1)
	ob = 0
	cb = 0
	c = 0
	count = 0
	for i in s:
		if i == '(':
			ob += 1
		else:
			cb += 1
		if cb > ob:
			s = s[:c] + s[c + 1:]
			s += [')']
			count += 1
			ob = cb = 0
		c += 1
	ar.append(count)
for i in ar:
	print(i)


for i in range(int(input())):
	n = input()
	n = input()
	while '()' in n:
		n = n.replace('()', '')
	print(int(len(n) / 2))


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	stack = []
	c = 0
	for i in range(len(s)):
		if s[i] == ')':
			if stack:
				stack.pop()
			else:
				c += 1
		if s[i] == '(':
			stack.append(s[i])
	print(min(c, len(stack)))


for i in range(int(input())):
	a = int(input())
	b = input()
	o = 0
	c = 0
	count = 0
	for i in range(len(b)):
		if b[i] == '(':
			o += 1
		if b[i] == ')':
			if o > 0:
				o -= 1
			else:
				count += 1
	print(count)


import math
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	c = 0
	d = 0
	k = w = 0
	for i in s:
		if i == '(':
			k += 1
		else:
			k -= 1
			if k < 0:
				k = 0
				w += 1
	print(w)


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	cur = ans = 0
	for i in range(n):
		if s[i] == '(':
			cur += 1
		else:
			cur -= 1
		ans = min(cur, ans)
	print(abs(ans))


t = int(input())
for _ in range(t):
	n = int(input())
	S = list(input())
	p = 0
	i = 0
	c = 0
	while i < len(S):
		if S[i] == '(':
			p += 1
			i += 1
		else:
			p -= 1
			if p < 0:
				del S[i]
				S.append(')')
				c += 1
				p = 0
			else:
				i += 1
	print(c)


n = int(input())
list_1 = []
for i in range(n):
	lon = int(input())
	s = input()
	while True:
		if '()' in s:
			s = s.replace('()', '')
		else:
			l = str(int(len(s) / 2))
			break
	list_1.append(l)
print('\n'.join(list_1))


tst = int(input())
for isa in range(tst):
	nsa = int(input())
	ssa = input()
	csa = 0
	osa = 0
	for jsa in range(nsa):
		if ssa[jsa] == '(':
			osa = osa + 1
		elif osa == 0:
			csa = csa + 1
		else:
			osa = osa - 1
	print(csa)


t = int(input())
for i in range(t):
	n = int(input())
	brackets = input()
	counter = 0
	u = 0
	for p in brackets:
		if p == '(':
			counter += 1
		elif p == ')':
			counter -= 1
		else:
			pass
		if counter == -1:
			counter = 0
			u += 1
		else:
			pass
	print(u)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	m = 0
	l = 0
	for j in range(n):
		if s[j] == '(':
			l -= -1
		else:
			l += -1
		m = min(m, l)
	print(-m)


for _ in range(int(input())):
	n = int(input())
	s = input()
	a = 0
	b = 0
	c = 0
	d = 0
	for i in s:
		if i == ')':
			a += 1
		else:
			break
	for i in s[::-1]:
		if i == '(':
			b += 1
		else:
			break
	op = 0
	cl = 0
	z = 0
	for i in range(a, len(s) - b):
		x = s[i]
		if x == '(':
			z += 1
			op += 1
		else:
			z -= 1
			cl += 1
		if z < 0:
			d += 1
			if s[i + 1] == '(':
				z = 0
	if op - cl > 0:
		c = op - cl
	x = 0
	x = min(a, b)
	if a > b:
		b = 0
		a -= b
	else:
		a = 0
		b -= a
	x += c + d
	print(x)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	li = []
	for i in range(len(s)):
		if s[i] == '(':
			li.append(s[i])
		elif s[i] == ')':
			if len(li) != 0 and li[-1] == '(':
				li.pop()
	print(len(li))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	l = list(s)
	i = 0
	while i < len(l):
		if l[i:i + 2] == ['(', ')']:
			l.pop(i + 1)
			l.pop(i)
			i -= 1
		else:
			i += 1
	print(len(l) // 2)


def answer(n, A):
	s = []
	for i in range(n):
		if A[i] == '(':
			s.append(A[i])
		elif len(s) != 0:
			s.pop()
	return len(s)
t = int(input())
for i in range(t):
	n = int(input())
	A = input()
	print(answer(n, A))


for ad in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	low = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < low:
			low = c
	print(abs(low))


test = int(input())

def solve():
	n = int(input())
	s = input()
	count1 = 0
	count2 = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == ')':
			if count1 == 0:
				ans += 1
			else:
				count1 -= 1
		else:
			count1 += 1
	print(ans)
while test:
	solve()
	test -= 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			c = 0
	print(c)


T = int(input())
while T > 0:
	n = int(input())
	s = input()
	miss = 0
	ope = 0
	for i in range(n):
		if s[i] == '(':
			ope += 1
		elif ope == 0:
			miss += 1
		else:
			ope -= 1
	print(miss)
	T -= 1


t = int(input())
while t:
	n = int(input())
	s = input()
	l = []
	x = 0
	count = 0
	for i in s:
		if i == '(':
			l.append(i)
			x += 1
		elif i == ')':
			if len(l) != 0 and l[x - 1] == '(':
				del l[x - 1]
				x = x - 1
			else:
				l.append(i)
				x += 1
	print(x // 2)
	t = t - 1


t = int(input())
while t:
	t = t - 1
	n = int(input())
	s = input()
	(op, count) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			op += 1
		elif op > 0:
			op -= 1
		else:
			count += 1
	print(count)


test = int(input())
for _ in range(test):
	(n,) = map(int, input().split())
	string = input()
	increase = 0
	decrease = 0
	for i in string:
		if i == '(':
			increase += 1
		elif increase == 0:
			decrease += 1
		else:
			increase -= 1
	print(decrease)


def irregularity(eile):
	current = 0
	irreg = 0
	for e in eile:
		if e == '(':
			current += 1
		else:
			current -= 1
		irreg = min(irreg, current)
	return -irreg
T = int(input())
for t in range(T):
	n = int(input())
	b = input()
	print(irregularity(b))


t = int(input())
for i in range(t):
	sum = 0
	n = int(input())
	s = input()
	a = 0
	for i in s:
		if i == '(':
			sum += 1
		elif sum > 0:
			sum -= 1
		else:
			a += 1
	print(a)


for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	op = 0
	cl = 0
	for i in s:
		if i == '(':
			op += 1
		elif i == ')':
			if op > 0:
				op -= 1
			else:
				cl += 1
	print(max(op, cl))


def main():
	n = int(input())
	ct = 0
	lines = []
	while ct < n * 2:
		line = [i for i in input()]
		if line:
			line = ''.join(line)
			lines.append(line)
			ct += 1
	bra = []
	for i in range(len(lines)):
		if i % 2 != 0:
			bra.append(lines[i])
	red = []
	for i in bra:
		while '()' in i:
			i = i.replace('()', '')
		else:
			red.append(i)
	for i in red:
		print(i.count('('))
main()


def main():
	n = int(input())
	s = input()
	o = 0
	c = 0
	d = 0
	for i in range(n):
		if s[i] == '(':
			o += 1
		elif s[i] == ')':
			c += 1
			if c > o + d:
				d += 1
	if o == c and d == 0:
		print(0)
	else:
		print(d)
t = int(input())
for _ in range(t):
	main()


t = int(input())
while t > 0:
	n = int(input())
	str = input()
	while '()' in str:
		str = str.replace('()', '')
	print(int(len(str) / 2))
	t = t - 1


t = int(input())
while t:
	n = int(input())
	s = input()
	cn = 0
	mm = 0
	for i in range(n):
		if cn < mm:
			mm = cn
		if s[i] == '(':
			cn += 1
		elif s[i] == ')':
			cn -= 1
	print(abs(mm))
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	x = 0
	y = 0
	c = 0
	for i in s:
		if i == ')':
			if y == 0:
				c += 1
			else:
				y -= 1
		elif i == '(':
			y += 1
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	copen = 0
	cclose = 0
	c = 0
	for i in s:
		if i == '(':
			copen = copen + 1
		else:
			cclose = cclose + 1
		if cclose > copen:
			cclose = cclose - 1
			c += 1
	print(c)


def get_wrong_index(s):
	number_of_open = 0
	ops = 0
	for (i, c) in enumerate(s):
		if c == '(':
			number_of_open += 1
		else:
			number_of_open -= 1
		if number_of_open < 0:
			ops += 1
			number_of_open = 0
	return ops

def solve():
	n = int(input())
	s = input().strip()
	return get_wrong_index(s)

def main():
	t = int(input())
	for i in range(t):
		print(solve())
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	front = -1
	numberofsteps = 0
	wrongpositions = []
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
			front += 1
		elif front != -1 and stack[front] == '(':
			front -= 1
		else:
			wrongpositions.append(i)
	print(len(wrongpositions))


from __future__ import division, print_function

def get_ints():
	return map(int, input().strip().split())

def get_array():
	return list(map(int, input().strip().split()))

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		arr = list(s)
		cnt = c = mx = 0
		for i in range(n):
			if arr[i] == '(':
				cnt += 1
			elif arr[i] == ')':
				cnt -= 1
			mx = min(cnt, mx)
		print(abs(mx))
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(n, s, cnt, ans) = (int(input()), input(), 0, 0)
	for c in s:
		if c == '(':
			cnt += 1
		else:
			cnt -= 1
			if cnt == -1:
				cnt = 0
				ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	string = input()
	stack = []
	for i in string:
		if i == '(':
			stack.append(i)
		elif i == ')':
			try:
				if stack[-1] == '(':
					stack.pop()
				else:
					stack.append(i)
			except:
				stack.append(i)
	print(len(stack) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	bracket = list(input())
	stack = []
	cnt = 0
	for x in bracket:
		if x == ')':
			if not stack:
				cnt += 1
			else:
				stack.pop()
		else:
			stack.append(x)
	print(cnt)


def main():
	t = int(input())
	for case in range(t):
		n = int(input())
		s = list(input())
		oc = 0
		count = 0
		i = 0
		while i < n:
			if s[i] == '(':
				oc += 1
				i += 1
			elif s[i] == ')':
				if oc > 0:
					oc -= 1
					i += 1
				else:
					s.pop(i)
					s.append(')')
					count += 1
		print(count)
main()


t = int(input())
for _ in range(t):
	x = int(input())
	s = input()
	o = 0
	a = 0
	c = 0
	for i in range(x):
		if s[i] == ')' and o == 0:
			a += 1
		if s[i] == ')' and o != 0:
			o -= 1
		elif s[i] == '(':
			o += 1
	print(a)


for test in range(int(input())):
	n = int(input())
	s = input()
	x = 0
	y = 0
	for i in range(n):
		if s[i] == '(':
			y += 1
		elif y == 0:
			x += 1
		else:
			y -= 1
	print(x)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	l = list(s)
	mn = 0
	c = 0
	for i in l:
		if i == '(':
			c += 1
		else:
			c -= 1
		mn = min(mn, c)
	print(mn * -1)


for _ in range(int(input())):
	n = int(input())
	str = input()
	cnt = 0
	mn = 0
	for i in range(len(str)):
		if str[i] == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < mn:
			mn = cnt
	print(abs(mn))


def ans(n, s):
	stack = []
	for i in range(n):
		if s[i] == '(':
			stack.append(i)
		if s[i] == ')':
			if len(stack) > 0:
				stack.pop(-1)
	return len(stack)
L = []
x = input()
for i in range(int(x)):
	n = int(input())
	s = input()
	L.append(int(ans(n, s)))
for l in L:
	print(l)


t = int(input())
for i in range(t):
	n = int(input())
	front = 0
	error = 0
	brackets = input()
	for j in brackets:
		if j == '(':
			front += 1
		else:
			front -= 1
		if front < 0:
			error += 1
			front = 0
	print(error)


for testcase in range(int(input())):
	n = int(input())
	s = input().strip()
	ans = 0
	sum = 0
	for ch in s:
		if ch == '(':
			sum += 1
		else:
			sum -= 1
		ans = max(ans, -sum)
	print(ans)


t = int(input())
for _ in range(t):
	a = input()
	n = input()
	while '()' in n:
		n = n.replace('()', '')
	print(len(n) // 2)


for _ in range(int(input())):
	n = int(input())
	l = list(input())
	o = miss = 0
	for i in range(n):
		if l[i] == '(':
			o += 1
		elif l[i] == ')':
			if o > 0:
				o -= 1
			else:
				miss += 1
	print(miss)


def f(s):
	o = 0
	c = 0
	count = 0
	for i in range(len(s)):
		if s[i] == '(':
			o += 1
		elif s[i] == ')':
			if o == c:
				count += 1
			elif o > c:
				c += 1
	return count
t = int(input())
for _ in range(t):
	input()
	s = input()
	print(f(s))


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	stack = []
	cnt = 0
	for s in string:
		if s == '(':
			stack.append(s)
		elif s == ')' and len(stack) > 0:
			stack.pop()
			cnt = cnt + 2
	print((n - cnt) // 2)


n_lines = int(input())
for _ in range(n_lines):
	n = int(input())
	brackets = list(input().rstrip('\n'))
	stack = []
	for b in brackets:
		if stack and stack[-1] == '(' and (b == ')'):
			stack.pop()
		else:
			stack.append(b)
	print(len(stack) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	abtk = 0
	ans = 0
	for i in s:
		if i == '(':
			abtk += 1
		elif abtk > 0:
			abtk -= 1
		else:
			abtk = 0
			ans += 1
	print(ans)


import collections as cc
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	s = list(input())
	ar = [0] * n
	for i in range(n):
		ar[i] = 1 if s[i] == '(' else -1
	for i in range(1, n):
		ar[i] += ar[i - 1]
	if min(ar) >= 0:
		print(0)
	else:
		print(-1 * min(ar))


for i in range(int(input())):
	n = int(input())
	s = input()
	a = 0
	b = 0
	for j in s:
		if j == '(':
			a += 1
		elif a > 0:
			a -= 1
		else:
			b += 1
	print((a + b) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	stri = input()
	right = []
	left = []
	for i in range(n):
		if stri[i] == ')':
			right.append(i)
		else:
			left.append(i)
	done = []
	for i in left:
		for j in right:
			if i < j and j not in done:
				done.append(j)
				break
	print(len(left) - len(done))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(str, input().strip()))
	maxi = 0
	summ = 0
	for i in range(n):
		if arr[i] == ')':
			summ += 1
		else:
			summ -= 1
		maxi = max(maxi, summ)
	print(maxi)


def solve():
	n = int(input())
	s = input()
	st = []
	count = 0
	for a in s:
		if a == '(':
			st.append(a)
		elif len(st) == 0:
			count += 1
		elif st[-1] == ')':
			count += 1
		else:
			st.pop()
	print(count)
t = int(input())
for _ in range(t):
	solve()


T = int(input())

def solve(s):
	count = 0
	i = 0
	countNeg = 0
	for i in range(0, len(s)):
		el = s[i]
		if el == '(':
			count += 1
		else:
			count -= 1
		if count == -1:
			countNeg += 1
			count = 0
	return countNeg
while T > 0:
	l = int(input())
	s = input()
	print(int(solve(s)))
	T -= 1


for i in range(int(input())):
	n = int(input())
	s = input()
	o = 0
	c = 0
	co = 0
	for i in range(len(s)):
		if s[i] == '(':
			o += 1
		if s[i] == ')':
			if i != 0 and o > 0:
				o = o - 1
			else:
				co += 1
	print(co)


ftot = int(input())
nlun = list('x') * ftot
pare = list('x') * ftot
(y, cont, c, d) = (0, 0, 0, 0)
(a, b) = ('(', ')')
for x in range(ftot):
	nlun[x] = int(input())
	pare[x] = input()
for x in range(ftot):
	pare[x] = list(pare[x])
while cont < ftot:
	y = 0
	while y < 25 and 0 < len(pare[cont]):
		y += 1
		d = 0
		x = 0
		while 0 < len(pare[cont]) - 1:
			d += 1
			if len(pare[cont]) - 1 > x and pare[cont][x] == a and (pare[cont][x + 1] == b):
				pare[cont].pop(x)
				pare[cont].pop(x)
			if len(pare[cont]) - 1 > x:
				x += 1
			if d > 49:
				break
	print(len(pare[cont]) // 2)
	cont += 1


size = int(input())
count = [0] * size
list = []
for i in range(0, size):
	lens = int(input())
	string = ''
	string = input()
	flag = [0] * int(lens)
	count = 0
	for m in range(len(string)):
		if string[m] == '(':
			for j in range(m, len(string)):
				if string[j] == ')' and flag[j] != 1:
					count += 2
					flag[j] = 1
					break
	list.append(int((int(lens) - count) / 2))
print(*list)


from collections import deque
n = int(input())
while n:
	n -= 1
	t = int(input())
	s = list(input())
	ans = 0
	i = 0
	curr = 0
	for i in s:
		if i == '(':
			curr += 1
		else:
			curr -= 1
			if curr < 0:
				ans += 1
				curr = 0
	print(ans)


t = int(input())
for i in range(t):
	k = int(input())
	s = input()
	state = 0
	ans = 0
	for j in s:
		if j == ')':
			if state == 0:
				ans += 1
			else:
				state -= 1
		else:
			state += 1
	print(ans)


def solve():
	stack = []
	for i in range(n):
		if not stack:
			stack.append(s[i])
		elif s[i] == ')':
			if stack and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(s[i])
		else:
			stack.append(s[i])
	print(len(stack) // 2)
for _ in range(int(input())):
	n = int(input())
	s = input()
	solve()


import sys
import copy
input = sys.stdin.readline
tc = int(input())
for _ in range(tc):
	n = int(input())
	arr = list(input().rstrip())
	s1 = list()
	s2 = list()
	for i in range(n):
		if arr[i] == '(':
			s1.append('(')
		elif s1 == []:
			s2.append(')')
		else:
			s1.pop(-1)
	print(len(s1))


import sys
I = sys.stdin.readline
pr = sys.stdout.write

def main():
	for _ in range(int(I())):
		I()
		s = I().strip()
		count = 0
		for ch in s:
			if ch == '(':
				count += 1
			elif count > 0:
				count -= 1
		pr(f'{count}\n')
main()


test = int(input())
for _ in range(test):
	n = int(input())
	astring = input()
	while True:
		n_prev = len(astring)
		astring = astring.replace('()', '')
		n = len(astring)
		if n_prev == n:
			break
	print(n // 2)


from sys import stdin
N = int(stdin.readline())
for _ in range(N):
	n = int(stdin.readline())
	string = stdin.readline().strip()
	ans = 0
	buf = 0
	for i in string:
		if i == ')':
			buf += 1
		elif i == '(':
			buf -= 1
		ans = max(ans, buf)
	print(ans)


ans = []
for i in range(int(input())):
	n = int(input())
	s = input()
	while 1:
		if '()' not in s:
			break
		else:
			s = s.replace('()', '')
	ans.append(s)
for i in ans:
	print(i.count('('))


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = deque()
	count = 0
	a = 0
	b = 0
	for i in range(n):
		if s[i] == ')':
			if len(stack) > 0:
				if stack[-1] == '(':
					a -= 1
					stack.pop()
				else:
					stack.append(s[i])
					b += 1
			else:
				stack.append(s[i])
				b += 1
		else:
			stack.append(s[i])
			a += 1
	print(min(a, b))


t = int(input())
for i in range(t):
	foo = input()
	s = input()
	stack = list()
	ans = 0
	for c in s:
		if c == '(':
			stack.append(c)
		elif len(stack) > 0:
			stack.pop()
		else:
			ans += 1
	print(ans)


t = int(input())
for q in range(t):
	n = int(input())
	ent = input()
	cont = 0
	ans = 0
	for k in range(n):
		if cont < 0:
			ans += 1
			cont += 1
		if ent[k] == '(':
			cont += 1
		else:
			cont -= 1
	print(ans)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	val = 0
	ans = 0
	for i in s:
		if i == '(':
			val += 1
		else:
			val -= 1
		if val < 0:
			val += 1
			ans += 1
	print(ans)


n = int(input())
strings = []
for i in range(n):
	x = input()
	strings.append(input())
for i in strings:
	stack = []
	for char in i:
		if char == '(':
			stack.append(char)
		elif not stack or stack[-1] != '(':
			stack.append(char)
		else:
			stack.pop()
	print(int(len(stack) / 2))


def main(n, s):
	Op = 0
	Cl = 0
	Tot = 0
	for i in s:
		if i == '(':
			Op += 1
		elif Op > 0:
			Op -= 1
			Tot += 1
	return int(n / 2 - Tot)
for i in range(int(input())):
	n = int(input())
	s = input()
	print(main(n, s))


for _ in range(int(input())):
	s = []
	n = int(input())
	l = input()
	for i in l:
		if not s:
			s.append(i)
		elif s[-1] == '(' and i == ')':
			s.pop()
		else:
			s.append(i)
	print(len(s) // 2)


q = int(input())
for Q in range(q):
	n = int(input())
	s = input()
	cop = 0
	clo = 0
	for ch in s:
		if ch == '(':
			cop += 1
		elif cop > 0:
			cop -= 1
		else:
			clo += 1
	print(cop)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = 0
	opening = 0
	closing = 0
	for i in range(n):
		if s[i] == '(':
			opening += 1
		else:
			closing += 1
		if closing > opening:
			ans += 1
			closing = 0
			opening = 0
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = input()
	c = 0
	m = 0
	for i in range(n):
		if arr[i] == '(':
			c = c + 1
		else:
			c = c - 1
		if c < 0:
			m = m + 1
			c = 0
	print(m)


def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def mi():
	return map(int, input().split())

def main():
	for i in range(ii()):
		n = ii()
		s = input()
		stack = []
		count = 0
		for i in s:
			if i == '(':
				stack.append(i)
			if i == ')':
				if stack == []:
					count += 1
				else:
					stack.pop()
		print(count)
main()


for i in range(int(input())):
	n = int(input())
	s = input()
	for j in range(51):
		if s.find('()') != -1:
			ind = s.find('()')
			s = s[:ind] + s[ind + 2:]
	print(s.count(')'))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
		elif stack[len(stack) - 1] == '(' and i == ')':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack) // 2)


def func(s, l):
	numOpens = 0
	mismatches = 0
	for i in range(l):
		if s[i] == '(':
			numOpens += 1
		elif numOpens <= 0:
			mismatches += 1
		else:
			numOpens -= 1
	return mismatches
t = int(input())
input_arr = []
for i in range(t):
	l = int(input())
	s = input()
	print(func(s, l))


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = 0
	ct = 0
	for i in s:
		if i == '(':
			stack += 1
		elif i == ')':
			if stack <= 0:
				ct += 1
			if stack > 0:
				stack -= 1
	print(ct)


testcases = int(input())
for i in range(testcases):
	n = int(input())
	brackets = input()
	left_close = 0
	right_open = 0
	for ele in brackets:
		if ele == '(':
			break
		left_close += 1
	for j in range(-1, -n - 1, -1):
		if brackets[j] == ')':
			break
		right_open += 1
	if left_close + right_open == n and left_close == right_open:
		print(right_open)
	else:
		left_open = 0
		no_pair = 0
		for ele in brackets:
			if ele == '(':
				left_open += 1
			elif left_open != 0:
				left_open -= 1
			else:
				no_pair += 1
		no_pair += left_open
		middle_no_pair = no_pair - (left_close + right_open)
		moves = 0
		if left_close == right_open:
			moves += left_close
			moves += middle_no_pair / 2
		elif left_close > right_open:
			moves += left_close
			moves += (middle_no_pair - (left_close - right_open)) / 2
		else:
			moves += right_open
			moves += (middle_no_pair - (right_open - left_close)) / 2
		print(int(moves))


def move(brack, posn, dir):
	li = list(brack)
	if dir == -1:
		ele = li[posn]
		li.pop(posn)
		li.insert(0, ele)
		brack = ''.join(li)
	else:
		ele = li[posn]
		li.pop(posn)
		li.append(ele)
		brack = ''.join(li)
	return brack

def brack_stack(brack):
	stack = []
	dit = {}
	for b in range(len(brack)):
		if brack[b] == '(':
			stack.append(brack[b])
			dit.update({b: brack[b]})
		elif brack[b] == ')':
			if len(stack) != 0:
				stack.pop(len(stack) - 1)
				keys = [key for key in dit.keys()]
				keys = keys[::-1]
				for key in keys:
					if dit[key] == '(':
						del dit[key]
						break
			else:
				dit.update({b: brack[b]})
	return dit
answers = []
tot_inp = int(input())
for inp in range(tot_inp):
	total = 0
	stack = []
	dit = {}
	length = int(input())
	brack = input()
	dit = brack_stack(brack)
	while len(dit) != 0:
		dit = brack_stack(brack)
		for (key, values) in dit.items():
			if values == '(':
				total += 1
				brack = move(brack, key, -1)
	answers.append(total)
for answer in answers:
	print(answer)


for _ in range(int(input())):
	a = int(input())
	b = input()
	(r, t) = (0, 0)
	for i in b:
		if i == '(':
			r += 1
		else:
			r -= 1
			if r == -1:
				t += abs(r)
				r = 0
	print(t)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt = 0
	(a, b) = (0, 0)
	res = 0
	for i in range(n):
		if s[i] == '(':
			cnt += 1
			if cnt <= 0:
				cnt = 1
		if s[i] == ')':
			if cnt > 0:
				res += 1
			cnt -= 1
	print(n // 2 - res)


n = int(input())
for i in range(n):
	a = int(input())
	b = str(input())
	for i in range(len(b) // 2):
		b = b.replace('()', '')
	print(len(b) // 2)


for i in range(int(input())):
	n = int(input())
	s = input()
	n_open = 0
	n_close = 0
	ans = 0
	for i in s:
		if i == '(':
			n_open += 1
		else:
			n_close += 1
		if n_close > n_open:
			if i == '(':
				ans += 1
			elif i == ')':
				ans += 1
				n_close -= 1
	print(ans)


for x in range(int(input())):
	n = int(input())
	s = input()
	s = list(s)
	while len(s) > 0:
		z = len(s)
		for i in range(z - 1):
			if s[i] == '(' and s[i + 1] == ')':
				s.pop(i)
				s.pop(i)
				break
		if len(s) == z or len(s) == 0:
			print(len(s) // 2)
			break


for i in range(int(input())):
	no_brackets = int(input())
	brackets = input()
	total = 1
	curr_string = brackets
	while True:
		temp = curr_string.replace('()', '')
		if temp == curr_string:
			break
		else:
			curr_string = temp
	print(int(len(curr_string) / 2))


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	b = 0
	for i in range(n):
		if s[i] == '(':
			b += 1
		elif s[i] == ')':
			if b == 0:
				ans += 1
			else:
				b -= 1
	ans += b
	print(ans // 2)


import math
import sys
import collections
from collections import defaultdict
from sys import stdin, stdout
MOD = 10 ** 9 + 7

def take_root(num):
	return math.ceil(math.sqrt(num))

def sieve():
	limit = 86028121
	isprime = [1] * 86028122
	isprime[0] = 0
	isprime[1] = 0
	for i in range(2, take_root(limit + 1)):
		if isprime[i] == 1:
			for j in range(i * i, limit + 1, i):
				isprime[j] = 0
	primes = []
	for i in range(limit + 1):
		if isprime[i] == True:
			primes.append(i)
	return primes

def minput():
	return map(int, input().split())

def iinput():
	return int(input())

def strinput():
	return input()

def linput():
	return list(map(int, input().split()))
for _ in range(iinput()):
	n = iinput()
	str1 = strinput()
	summ = 0
	cnt = 0
	for i in range(n):
		if str1[i] == ')':
			summ -= 1
		elif str1[i] == '(':
			summ += 1
		if summ < 0:
			cnt += 1
			summ = 0
	print(cnt)


t = int(input())
for u in range(t):
	n = int(input())
	s = input()
	otk = 0
	otv = 0
	for i in s:
		if i == '(':
			otk += 1
		elif otk > 0:
			otk -= 1
		else:
			otv += 1
	print(otv)


for _ in range(int(input())):
	n = int(input())
	s = input()
	s = s
	stack = [')']
	ans = 0
	for i in range(n):
		if s[i] == ')' and stack[len(stack) - 1] == ')':
			ans += 1
			stack.append(')')
		elif s[i] == ')' and stack[len(stack) - 1] == '(':
			stack.pop()
		elif s[i] == '(':
			stack.append('(')
	print(ans)


def solve():
	n = int(input())
	s = input()
	ans = 0
	for i in range(n):
		if s[i] == '(':
			ans += 1
		elif ans > 0:
			ans -= 1
	print(ans)
for _ in range(int(input())):
	solve()


t = int(input())
for dffg in range(t):
	n = int(input())
	A = list(input())
	ans = 0
	while n != 0:
		if A[0] == '(':
			A.remove(A[0])
			a = A.index(')')
			A.remove(A[a])
			n -= 2
		else:
			b = A[0]
			A.remove(b)
			A.append(b)
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	stack = []
	A = 0
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif s[i] == ')':
			if stack:
				if stack[-1] == '(':
					stack.pop()
			else:
				A += 1
	print(A)


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	openCount = 0
	ans = 0
	for i in string:
		if i == '(':
			openCount += 1
		elif i == ')':
			openCount -= 1
		if openCount < 0:
			ans += 1
			openCount = 0
	print(ans)


t = int(input())
for i in range(t):
	length = int(input())
	string = input()
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	string = string.replace('()', '')
	length = len(string)
	string = [i for i in string]
	duplicate = string.copy()
	haha = False
	regulars = []
	leftBoundary = length / 2 - 1
	leftOnRight = 0
	rightOnLeft = 0
	answer = 0
	for j in range(len(string)):
		if string[j] == ')' and j <= leftBoundary:
			rightOnLeft += 1
		elif string[j] == '(' and j > leftBoundary:
			leftOnRight += 1
	if leftOnRight > rightOnLeft:
		print(str(rightOnLeft - len(regulars)))
	else:
		print(str(leftOnRight - len(regulars)))


t = int(input(''))
while t > 0:
	n = int(input(''))
	s = input('')
	count = 0
	ans = 0
	index = 0
	for i in s:
		if i == ')':
			count -= 1
		if i == '(':
			count += 1
		if count < 0:
			count = 0
			ans += 1
		index += 1
	print(ans)
	t -= 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(el, er, l, r) = (0, 0, 0, 0)
	for c in s:
		if c == '(':
			l += 1
		else:
			r += 1
			if r >= l:
				er += r - l
				(l, r) = (0, 0)
			else:
				l -= r
				r = 0
	el += l
	er += r
	print(el)


t = int(input())
for i in range(t):
	l = int(input())
	s = list(input())
	stack = []
	moves = 0
	indx = 0
	while indx < l or stack != []:
		if s[indx] == '(':
			stack.append('(')
			indx += 1
		elif len(stack) > 0:
			stack.pop()
			indx += 1
		else:
			moves += 1
			s.pop(indx)
			s.append(')')
	print(moves)


def Hello(n, s):
	s = list(s)
	k = []
	for e in s:
		if e == '(':
			k.append(e)
		elif len(k) > 0 and k[-1] == '(' and (e == ')'):
			k.pop()
		else:
			k.append(e)
	l = len(k) // 2
	return l
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(Hello(n, s))


def func(n, m):
	if n == 1:
		return m
	elif n < 6:
		return func(2 * n, m + 1)
	elif n <= 0:
		return 1
	elif n % 6 == 0:
		return func(n // 6, m + 1)
	elif n % 3 == 0:
		return func(2 * n, m + 1)
	else:
		return -1
from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = 0
	stack = deque()
	for i in range(n):
		if s[i] == '(':
			stack.append(s[i])
		elif s[i] == ')':
			if len(stack) > 0:
				if stack.pop() == '(':
					c += 2
				else:
					while len(stack) > 0:
						stack.pop()
	print((n - c) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	s = list(s)
	ans = 0
	countb = 0
	countf = 0
	for j in range(n):
		if s[j] == '(':
			countf += 1
		elif s[j] == ')':
			countb += 1
		if countb > countf:
			ans += countb - countf
			countb = 0
			countf = 0
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	s = input()
	cnt = 0
	res = 0
	while True:
		if s.find('()') == -1:
			break
		s = s.replace('()', '')
	print(s.count('('))


for i in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for j in range(n):
		if s[j] == '(':
			c += 1
		elif c > 0:
			c -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	l1 = input()
	A = input()
	st = []
	for i in range(len(A)):
		if A[i] == '(':
			st.append(A[i])
		if A[i] == ')':
			if '(' in st:
				st.pop()
			else:
				st.append(A[i])
	print(int(len(st) / 2))


try:
	k = int(input())
	for i in range(k):
		n = int(input())
		s = input()
		a = 0
		l = []
		for i in range(n):
			if s[i] == '(':
				a += 1
			else:
				a -= 1
			l.append(a)
		l.sort()
		print(abs(l[0]))
except:
	pass


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	diff = 0
	res = 0
	for letter in s:
		if letter == '(':
			diff += 1
		elif diff > 0:
			diff -= 1
		else:
			res += 1
	print(res)


t = int(input())
l = []
for i in range(t):
	n = int(input())
	s = input()
	count1 = 0
	count0 = 0
	for i in range(n):
		if count1 == 0 and s[i] == ')':
			count0 = count0 + 1
		elif s[i] == '(':
			count1 = count1 + 1
		elif s[i] == ')' and count1 != 0:
			count0 = count0 - 1
			count1 = count1 - 1
	l.append(count1)
for i in l:
	print(i)


from sys import stdin
from math import *
from random import randint
from collections import deque

def splt():
	return map(int, stdin.readline().split())
test = int(input())
for i in range(test):
	n = int(input())
	st = input()
	ans = 99999999
	x = 0
	for i in range(n):
		if st[i] == ')':
			x -= 1
		else:
			x += 1
		ans = min(ans, x)
	print(abs(ans))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	opening = 0
	closing = 0
	ans1 = []
	for j in range(n):
		if s[j] == '(':
			opening += 1
		else:
			closing += 1
			ans1.append(closing - opening)
	print(max(ans1))


import sys
import math
import heapq
from collections import defaultdict, deque
input = sys.stdin.readline

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
for _ in range(r()):
	n = r()
	a = list(input())
	a = a[:-1]
	n = len(a)
	i = 0
	cnt = 0
	chn = 0
	while i < n:
		if a[i] == ')':
			chn -= 1
		else:
			chn += 1
		if chn == -1:
			cnt += 1
			a.append(')')
			n += 1
			chn = 0
		i += 1
	print(cnt)


test = int(input())
for _ in range(test):
	n = int(input())
	k = input()
	l = []
	for i in range(n):
		if k[i] == '(':
			l.append(k[i])
		elif len(l) > 0 and l[-1] == '(':
			l.pop()
	print(len(l))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far
from math import *

def check(st):
	(start, end) = (0, 0)
	for i in range(len(st)):
		if st[i] == '(':
			start += 1
		else:
			end += 1
		if end > start:
			return 1
	return 0
for _ in range(int(input())):
	n = int(input())
	st = input()
	(start, end) = (0, 0)
	cnt = 0
	for i in range(n):
		for i in range(len(st)):
			if st[i] == '(':
				start += 1
			else:
				end += 1
			if end > start:
				(start, end) = (0, 0)
				cnt += 1
	print(cnt)


t = int(input())
for i in range(t):
	stack = []
	n = input()
	input_stack = input()
	consider = []
	for j in input_stack:
		if len(consider) > 0:
			if j == ')' and consider[-1] == '(':
				consider.pop()
			else:
				consider.append(j)
		else:
			consider.append(j)
	print(len(consider) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	count = 0
	for i in s:
		if i == '(':
			stack.append('(')
		elif stack:
			stack.pop()
		else:
			count += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = input()
	open_b = 0
	close_b = 0
	for i in s:
		if i == '(':
			open_b += 1
		elif open_b != 0:
			open_b -= 1
		else:
			close_b += 1
	print(close_b)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		no = nc = moves = 0
		for i in s:
			if i == '(':
				no += 1
			else:
				nc += 1
				if nc > no + moves:
					moves += 1
		print(moves)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	x = 0
	y = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			x = x + 1
			if x > y:
				ans = ans + 1
				x = x - 1
		else:
			y = y + 1
	print(ans)


t = int(input())
cnt = 0
while cnt < t:
	cnt += 1
	n = int(input())
	s = input()
	bal = 0
	min_bal = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if min_bal > bal:
				min_bal = bal
	print(abs(min_bal))


for _ in range(int(input())):
	n = int(input())
	a = input()
	while a.count('()') > 0:
		a = a.replace('()', '')
	print(a.count('('))


t = int(input())
for _ in range(t):
	n = int(input())
	brackets = input()
	open_ = 0
	close_ = 0
	for br in brackets:
		if br == '(':
			open_ += 1
		if open_ != 0 and br == ')':
			open_ -= 1
		elif open_ == 0 and br == ')':
			close_ += 1
	if open_ == close_:
		print(open_)


for _ in range(int(input())):
	deq = []
	n = int(input())
	s = list(input().strip())
	i = 0
	count = 0
	while i < len(s):
		if s[i] == '(':
			deq.append('(')
			i += 1
			continue
		if deq:
			deq.pop()
		else:
			s.append(')')
			count += 1
		i += 1
	print(count)


k = int(input())
for i in range(k):
	a = int(input())
	lis = list(input())
	maxlen = 0
	s = []
	for j in range(a):
		if lis[j] != '(':
			if maxlen != 0:
				s.pop()
				maxlen = maxlen - 1
		else:
			s.append(lis[j])
			maxlen = maxlen + 1
	print(maxlen)


t = int(input())
for i in range(t):
	s = int(input())
	q = input()
	cnt = 0
	f = 0
	for i in range(s):
		if q[i] == '(':
			cnt += 1
		else:
			cnt -= 1
		f = min(f, cnt)
	print(abs(f))


t = int(input())
for l in range(t):
	n = int(input())
	s = input()
	sum = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			sum += 1
		else:
			sum -= 1
			if sum < 0:
				ans += 1
				sum += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	S = list(input())
	A = [0, 0]
	ans = 0
	for i in range(n):
		if S[i] == '(':
			A[0] += 1
		else:
			A[1] += 1
		a = A[1] - A[0]
		if a > ans:
			ans = a
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [i for i in input()]
	k = 0
	dic = {'(': 1, ')': -1}
	ans = 0
	for i in arr:
		k += dic[i]
		if k < 0:
			k = 0
			ans += 1
	print(ans)


from sys import stdin, stdout
import math
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	st = []
	cnt = 0
	for c in s:
		if c == '(':
			st.append(c)
		elif not st:
			cnt += 1
		else:
			st.pop()
	print(cnt)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	(left, right) = (0, 0)
	for i in range(n):
		if s[i] == ')' and left > 0:
			left -= 1
		elif s[i] == ')':
			right += 1
		else:
			left += 1
	print((left + right) // 2)


import math, string, itertools, operator, fractions, heapq, collections, re, array, bisect, sys, functools

def solve(line):
	n = int(line)
	s = sys.stdin.readline().rstrip()
	c = []
	cs = 0
	ans = 0
	for i in s:
		if i == ')':
			cs -= 1
		if i == '(':
			if cs < 0:
				c.append(cs)
				cs = 0
			cs += 1
	return -sum(c)
T = int(sys.stdin.readline())
t = 0
while True:
	line = sys.stdin.readline().rstrip()
	if not line:
		break
	print(solve(line))
	t += 1


n = int(input())
for _ in range(n):
	x = int(input())
	s = input()
	kolz = 0
	kolo = 0
	ans = 0
	for i in s:
		if i == '(':
			kolo += 1
		else:
			kolz += 1
		if kolz > kolo:
			ans += kolz - kolo
			kolz = kolo
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	cnt = 0
	broken_index = 0
	while True:
		broken = 0
		stack = [s[broken_index]]
		while stack[0] == ')':
			s.append(s.pop(0))
			stack = [s[broken_index]]
			cnt += 1
		stack = [s[broken_index]]
		for i in range(broken_index + 1, n):
			if len(stack):
				if stack[-1] == '(':
					if s[i] == '(':
						stack.append('(')
					else:
						stack.pop()
				else:
					broken_index = i
					broken = 1
					break
			elif s[i] == '(':
				stack.append('(')
			else:
				broken_index = i
				broken = 1
				break
		if broken:
			s.append(s.pop(broken_index))
			cnt += 1
		else:
			print(cnt)
			break


t = int(input())
for i in range(t):
	n = int(input())
	s = list(input())
	(m, curr) = (0, 0)
	for w in s:
		if w == '(':
			curr += 1
		else:
			curr -= 1
		m = min(curr, m)
	print(-m)


t = int(input())
for _ in range(t):
	n = int(input())
	ar = input()
	bal = 0
	mbal = 0
	for i in ar:
		if i == ')':
			bal += 1
		else:
			bal -= 1
		mbal = max(bal, mbal)
	print(mbal)


from fractions import Fraction
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
import statistics
from statistics import mode
mod = 1000000007

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def most_frequent(List):
	occurence_count = Counter(List)
	return occurence_count.most_common(1)[0][0]

def most_common(List):
	return mode(List)

def createMatrix(rowCount, colCount, dataList):
	mat = []
	for i in range(rowCount):
		rowList = []
		for j in range(colCount):
			if dataList[j] not in mat:
				rowList.append(dataList[j])
		mat.append(rowList)
	return mat

def isprime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
import collections

def minimalFilps1(bits):
	n = len(bits)
	flipsFromLeft = [0 for i in range(n)]
	flipsFromRight = [0 for i in range(n)]
	flips = 0
	for i in range(0, n, 1):
		if bits[i] == '1':
			flips = flips + 1
		flipsFromLeft[i] = flips
	flips = 0
	i = n - 1
	while i >= 0:
		if bits[i] == '0':
			flips = flips + 1
		i = i - 1
		flipsFromRight[i] = flips
	minFlips1 = sys.maxsize
	for i in range(1, n, 1):
		if flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips1:
			minFlips1 = flipsFromLeft[i - 1] + flipsFromRight[i]
	return minFlips1

def minimalFilps(bits):
	n = len(bits)
	flipsFromLeft = [0 for i in range(n)]
	flipsFromRight = [0 for i in range(n)]
	flips = 0
	for i in range(0, n, 1):
		if bits[i] == '0':
			flips = flips + 1
		flipsFromLeft[i] = flips
	flips = 0
	i = n - 1
	while i >= 0:
		if bits[i] == '1':
			flips = flips + 1
		i = i - 1
		flipsFromRight[i] = flips
	minFlips = sys.maxsize
	for i in range(1, n, 1):
		if flipsFromLeft[i - 1] + flipsFromRight[i] < minFlips:
			minFlips = flipsFromLeft[i - 1] + flipsFromRight[i]
	return minFlips

def oddn(n):
	for i in range(2, n + 1):
		if i % 2 != 0 and n % i == 0:
			return i
	return 3

def memoized(*args):
	if args in stored_results:
		return stored_results[args]
	else:
		result = stored_results[args] = fn(*args)
		return result
	return memoized
import operator
open_list = ['(']
close_list = [')']

def check(myStr):
	stack = []
	e = 0
	for i in myStr:
		if i in open_list:
			stack.append(i)
		elif i in close_list:
			pos = close_list.index(i)
			if len(stack) > 0:
				stack.pop()
				e += 1
	return e
for i in range(int(input())):
	n = int(input())
	s = input()
	b = check(s)
	c = 0
	if b == n // 2:
		c = 0
	else:
		c = (n - 2 * b) // 2
	print(c)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	op = 0
	cl = 0
	req = 0
	out = 0
	if s[0] == '(':
		op = 1
		for j in range(1, n):
			out = min(op, out)
			if s[j] == ')':
				op -= 1
			else:
				op += 1
	elif s[0] == ')':
		cl = -1
		for j in range(1, n):
			out = min(cl, out)
			if s[j] == '(':
				cl += 1
			else:
				cl -= 1
	print(abs(out))


for i in range(int(input())):
	n = int(input())
	s = input()
	res = 0
	cntl = 0
	cntr = 0
	for j in range(n):
		if s[j] == '(':
			cntl += 1
		else:
			cntr += 1
			if cntr > cntl:
				res = max(res, cntr - cntl)
	print(res)


for i in range(int(input())):
	n = int(input())
	s = input()
	x = True
	while x:
		x = False
		if '()' in s:
			x = True
			s = s.replace('()', '')
	print(int(len(s) / 2))


for _ in range(int(input())):
	n = int(input())
	a = input()
	s = []
	for i in range(n):
		s.append(a[i])
	cnt = 0
	f = 0
	for i in range(n):
		if s[i] == ')':
			if f <= 0:
				cnt += 1
			else:
				f -= 1
		elif s[i] == '(':
			f += 1
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	s = input()
	visited = [False] * n
	for i in range(n):
		if s[i] == '(':
			for j in range(i, n):
				if s[j] == ')' and visited[j] == False:
					visited[i] = True
					visited[j] = True
					break
	cnt = 0
	for i in visited:
		if i == False:
			cnt += 1
	print(cnt // 2)


for ii in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	m = 0
	for i in s:
		if i == ')':
			ans += 1
		else:
			ans -= 1
		m = max(ans, m)
	print(m)


t = int(input())
for t in range(t):
	n = int(input())
	paren = str(input())
	brackets = []
	for parenthesis in paren:
		brackets.append(parenthesis)
	rup = 0
	ltp = 0
	for i in range(len(brackets)):
		if brackets[i] == '(':
			ltp += 1
		if brackets[i] == ')':
			if ltp >= 1:
				ltp -= 1
			else:
				rup += 1
	print(rup)


for _ in range(int(input())):
	(_, s) = (input(), input())
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


T = int(input())
for i in range(T):
	x = int(input())
	ls = input()
	count = 0
	newls = []
	for i in range(x):
		if ls[i] == '(':
			newls.append(ls[i])
		elif ls[i] == ')':
			if len(newls):
				newls.pop(0)
			else:
				count += 1
	print(count)


for i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	curr = 0
	for ch in s:
		if ch == '(':
			curr += 1
		else:
			curr -= 1
		if curr < 0:
			ans += 1
			curr = 0
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cur_bal = 0
	r = 1
	for i in range(len(s)):
		if s[i] == '(':
			cur_bal += 1
		elif s[i] == ')':
			cur_bal -= 1
		r = min(r, cur_bal)
	print(abs(r))


T = int(input())
for t in range(T):
	L = int(input())
	S = list(input())
	st = 0
	rr = 0
	for l in range(L):
		if S[l] == '(':
			st += 1
		elif S[l] == ')':
			if st > 0:
				st -= 1
			else:
				rr += 1
	print(rr)


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		d = deque([])
		n = iin()
		s = sin()
		for i in s:
			if len(d) == 0:
				d.append(i)
			elif i == ')':
				if d[-1] == '(':
					d.pop()
				else:
					d.append(i)
			else:
				d.append(i)
		print(len(d) // 2)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
while t:
	n = int(input())
	s = input()
	st = []
	for val in s:
		if st:
			if val == ')' and st[-1] == '(':
				st.pop()
			else:
				st.append(val)
		else:
			st.append(val)
	print(len(st) // 2)
	t -= 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	l = []
	while '()' in s:
		s = s.replace('()', '')
	print(s.count(')'))


def main():
	n = int(input())
	brackets = input()
	(cnt, res, i) = (0, 0, 0)
	while i < n:
		if brackets[i] == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			brackets = brackets[:i] + brackets[i:] + ')'
			res += 1
			cnt = 0
		i += 1
	return res
tests = int(input())
while tests:
	tests -= 1
	print(main())


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	(c1, p) = (0, 0)
	for c in s:
		if c == '(':
			p -= 1
		else:
			p += 1
		c1 = max(c1, p)
	print(c1)
	t -= 1


for i in range(int(input())):
	input()
	z = input()
	(v, ans) = ([], 0)
	for i in z:
		if i == '(':
			v.append(i)
		elif len(v) == 0:
			ans += 1
		else:
			v.pop()
	print(ans)


N = int(input())
i = 0
while i < N:
	n = input()
	s = input()
	stack = []
	size = 0
	for c in s:
		if c == '(':
			stack.append('(')
		elif stack and stack[-1] == '(':
			stack.pop()
		else:
			stack.append(')')
	print(stack.count(')'))
	i += 1


t = int(input())
while t:
	t += -1
	n = int(input())
	s = input()
	cnt = 0
	ans = 0
	for i in s:
		if i == '(':
			cnt += -1
		else:
			cnt -= -1
		ans = max(ans, cnt)
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	tmp = 0
	mi = 0
	for c in s:
		tmp += 1 if c == '(' else -1
		mi = min(mi, tmp)
	print(-mi)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	open_b = 0
	close_b = 0
	ans = 0
	for j in range(n):
		if s[j] == '(':
			open_b += 1
		else:
			close_b += 1
		if open_b < close_b:
			close_b -= 1
			ans += 1
	print(ans)


def solve():
	x = int(input())
	y = input()
	stack = []
	prev = 0
	for i in y:
		if i == '(':
			stack.append(i)
			prev += 1
		elif i == ')' and prev > 0:
			if len(stack) != 0:
				stack.pop()
			prev -= 1
		else:
			stack.append(i)
	print(len(stack) // 2)
tc = int(input())
for i in range(tc):
	solve()


for _ in range(int(input())):
	n = int(input())
	s = input()
	lst = []
	open1 = 0
	ct = 0
	for i in s:
		if i == '(':
			open1 += 1
		elif i == ')' and open1 > 0:
			open1 -= 1
		elif i == ')' and open1 == 0:
			ct += 1
	print(ct)


t = int(input())
for w in range(t):
	n = int(input())
	s = input()
	s1 = 0
	m = 0
	for i in range(n):
		if s[i] == ')':
			s1 += 1
		else:
			s1 -= 1
		m = max(m, s1)
	print(m)


for _ in range(int(input())):
	n = int(input())
	str = input()
	count = 0
	ans = 0
	for i in range(n):
		if str[i] == '(':
			count += 1
		elif str[i] == ')':
			count -= 1
		if count < 0:
			count = 0
			ans += 1
	print(ans)


import sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
import string

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' ', end='\n'):
	print(sep.join(map(str, a)), end=end)

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
for _ in range(ii()):
	n = ii()
	s = input()
	o = c = res = 0
	for i in s:
		if i == '(':
			o += 1
		else:
			c += 1
		if c > o:
			res += 1
			c -= 1
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	f = True
	j = 0
	ans = 0
	while f:
		f = False
		for i in range(j, n):
			if s[i] == '(':
				c += 1
			else:
				c -= 1
			if c < 0:
				f = True
				ans += 1
				c = 0
				j = i
				s = s[:i] + s[i + 1:] + s[i]
				break
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	d = []
	c = []
	v = 0
	for i in s:
		if i == '(':
			d.append('(')
		elif d != [] and i == ')' and (d[-1] == '('):
			d.pop()
		else:
			v += 1
	print(v)


def solve(n, s):
	sol = depth = 0
	for c in s:
		if c == '(':
			depth += 1
		else:
			depth -= 1
			if depth < 0:
				depth = 0
				sol += 1
	return sol
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(solve(n, s))


import math
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	summ = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			summ += 1
		else:
			summ -= 1
		if summ == -1:
			ans += 1
			summ = 0
	print(ans)


def movebrackets(text):
	o = 0
	c = 0
	stck = []
	for i in text:
		if i == ')' and (len(stck) > 0 and stck[-1] == '('):
			stck.pop()
		else:
			stck.append(i)
	for i in stck:
		if i == '(':
			o += 1
		else:
			c += 1
	return o
t = int(input())
while t > 0:
	n = int(input())
	txt = input()
	print(movebrackets(txt))
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	c = 0
	t = 0
	for i in s:
		if i == ')' and c == 0:
			t = t + 1
		if i == '(':
			c = c - 1
		if i == ')' and c != 0:
			c = c + 1
	print(t)


N = int(input())
for i in range(N):
	m = int(input())
	s = input()
	total_list = list(range(m))
	total = 0
	for j in range(m):
		char = s[j]
		if char == '(':
			total += 1
		else:
			total -= 1
		total_list[j] = total
	output = abs(min(total_list))
	print(output)


t = int(input())
p = []
q = []
for i in range(t):
	u = int(input())
	y = input()
	p.append(u)
	q.append(y)

def api(n, arr):
	count = 0
	ans = 0
	for i in range(n):
		if arr[i] == '(':
			count += 1
		elif arr[i] == ')':
			if count > 0:
				count -= 1
			else:
				ans += 1
	return ans
for i in range(t):
	r = api(p[i], q[i])
	print(r)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	newnumber = 0
	while number > 0:
		newnumber += number % base
		number //= base
	return newnumber

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True
for _ in range(ii()):
	n = ii()
	s = input()
	bal = 0
	b = []
	for c in s:
		if c == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			b.append(bal)
	print(-min(b) if b else 0)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	stack = []
	for i in s:
		if i == '(':
			stack.append('(')
		if i == ')':
			if len(stack) != 0 and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
	print(len(stack) // 2)
	t -= 1


t = int(input())
for t in range(t):
	p = int(input())
	q = input()
	j = 0
	for i in range(len(q)):
		if q[i] == '(':
			j += 1
		elif j != 0:
			j -= 1
	print(j)


import sys
t = int(sys.stdin.readline())
ans_arr = []
for i in range(t):
	n = int(sys.stdin.readline())
	s = sys.stdin.readline().strip()
	ctr = 0
	ans = 0
	for g in range(len(s)):
		if s[g] == '(':
			ctr += 1
		elif ctr - 1 < 0:
			ans += 1
		else:
			ctr -= 1
	ans_arr.append(str(ans))
print('\n'.join(ans_arr))


done = False
min_ops = 10000000000

def isBracketValid(s):
	arr = []
	index = -1
	for i in s:
		index += 1
		if i == '(':
			arr.append('(')
		else:
			if len(arr) == 0:
				return index
			bracket = arr.pop()
			if bracket != '(':
				return index
	return -1

def makeValidate(s, ops):
	global done
	global min_ops
	if done == True:
		return
	index = isBracketValid(s)
	if index == len(s) or index == -1:
		done = True
		if ops < min_ops:
			min_ops = ops
	else:
		strObj = s[0:index] + s[index + 1:]
		newops = ops + 1
		if index != len(s) - 1:
			newStr = strObj + s[index]
			makeValidate(newStr, newops)
		if index != 0:
			newStr = s[index] + strObj
			makeValidate(newStr, newops)
	return
t = int(input())
while t:
	t -= 1
	l = int(input())
	brackets = str(input())
	ind = isBracketValid(brackets)
	if ind == -1 or ind == len(brackets):
		print('0')
	else:
		ops = 0
		done = False
		min_ops = 10000000000000
		makeValidate(brackets, ops)
		print(min_ops)


t = int(input())
for _ in range(t):
	count = 0
	count1 = 0
	x = int(input())
	a = input()
	b = list(a)
	for i in range(len(b)):
		if b[i] == ')':
			count -= 1
		else:
			count += 1
		if count == -1:
			count1 += 1
			count = 0
	print(count1)


import sys

def swap(x, y, a):
	temp = a[x]
	a[x] = a[y]
	a[y] = temp
	return a

def solve(s, p):
	curr = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == p:
			curr += 1
		else:
			curr -= 1
		if curr < 0:
			ans += 1
			curr += 1
	return ans

def main():
	q = []
	for line in sys.stdin.readlines():
		q.append(line)
	for i in range(len(q)):
		q[i] = q[i].rstrip().split(' ')[0]
	for i in range(1, len(q), 2):
		s = q[i + 1]
		r = s[::-1]
		ans = solve(s, '(')
		ans = min(ans, solve(r, ')'))
		print(ans)
main()


from itertools import accumulate
t = int(input())
for case in range(t):
	n = int(input())
	s = [1 if i == '(' else -1 for i in input()]
	x = list(accumulate(s))
	print(-min(x))


for _ in range(int(input())):
	n = int(input())
	s = [bracket for bracket in input()]
	opening = 0
	closing = 0
	for bracket in s:
		if bracket == '(':
			opening += 1
		elif opening != 0:
			opening -= 1
		else:
			closing -= 1
	print(abs(closing))


for _ in range(int(input())):
	n = int(input())
	st = input()
	(ct, an) = (0, 0)
	for chr in st:
		if chr == ')':
			if ct == 0:
				an += 1
			else:
				ct += 1
		else:
			ct -= 1
	print(an)


import sys
from collections import deque
t = int(input())

def inp():
	return sys.stdin.readline().strip()
for _ in range(t):
	n = int(inp())
	s = inp()
	st = deque()
	for i in s:
		if i == ')':
			if len(st) != 0 and st[-1] == '(':
				st.pop()
			else:
				st.append(')')
		else:
			st.append('(')
	ans = len(st) // 2
	print(ans)


def func(string):
	count = 0
	op = 0
	close = 0
	for i in string:
		if i == ')':
			if op == 0:
				close += 1
			else:
				op -= 1
		else:
			op += 1
	return close
t = int(input())
for _ in range(t):
	a = int(input())
	string = input()
	print(func(string))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = 0
	for b in s:
		if b == '(':
			c += 1
		elif c > 0:
			c -= 1
	print(c)


t = int(input())
for i in range(t):
	n = int(input())
	s = list(input())
	c = 0
	mn = 0
	for j in range(n):
		if s[j] == '(':
			c += 1
		else:
			c -= 1
		mn = min(c, mn)
	print(abs(mn))


t = int(input())
for _ in range(t):
	n = int(input())
	bracket_arr = list(input())
	balance_arr = [False] * n
	balancing_dict = {}
	curr = 0
	for i in range(n):
		if bracket_arr[i] == '(':
			curr += 1
			balancing_dict[curr] = i
		else:
			curr -= 1
			if curr == -1:
				curr = 0
			else:
				balance_arr[balancing_dict[curr + 1]] = True
				balance_arr[i] = True
				del balancing_dict[curr + 1]
	number_opening_after = [0] * n
	number_closing_before = [0] * n
	curr = 0
	val = 0
	for i in range(n - 1, -1, -1):
		if bracket_arr[i] == '(' and balance_arr[i] == False:
			curr += 1
			val += 1
		number_opening_after[i] = val
	curr = 0
	val = 0
	for i in range(n):
		if bracket_arr[i] == ')' and balance_arr[i] == False:
			curr += 1
			val += 1
		number_closing_before[i] = val
	opening_used = 0
	closing_used = 0
	moves = 0
	for i in range(n):
		if bracket_arr[i] == '(' and number_closing_before[i] - closing_used > 0:
			moves += 1
			opening_used += 1
			closing_used += 1
		if balance_arr[i] == ')' and number_opening_after[i] - opening_used > 0:
			moves += 1
			opening_used += 1
			closing_used += 1
	print(moves)


class Solution:

	def solve(self, s):
		open_count = 0
		for c in s:
			if c == '(':
				open_count += 1
			elif open_count > 0:
				open_count -= 1
		return open_count
for _ in range(int(input())):
	_ = int(input())
	s = input()
	ans = Solution().solve(s)
	print(ans)


t = int(input())
k = []
for i in range(t):
	n = int(input())
	s = input()
	l = 0
	r = 0
	for j in range(len(s)):
		if s[j] == ')' and l == 0:
			r += 1
		if s[j] == ')' and l != 0:
			l -= 1
		if s[j] == '(':
			l += 1
	k.append(l)
for i in range(t):
	print(k[i])


def main():
	n = int(input())
	s = input()
	count = 0
	for i in range(n):
		s = s.replace('()', '')
	return len(s) // 2
t = int(input())
for i in range(t):
	print(main())


import sys
sys.setrecursionlimit(10 ** 9)

def mod(a, i, n):
	if i < n - 1:
		if a[i] == '(' and a[i + 1] == ')':
			a.pop(i)
			a.pop(i)
			n = len(a)
			return mod(a, i, n)
		else:
			return mod(a, i + 1, n)
	else:
		return a
for _ in range(int(input())):
	n = int(input())
	s = input()
	a = [i for i in s]
	n = len(a)
	for i in range(25):
		i = 0
		if n >= 2:
			a = mod(a, i, n)
		else:
			break
		n = len(a)
	print(len(a) // 2)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	min_moves = 0
	x = []
	flip = 0
	for i in range(n):
		if s[i] == '(':
			flip += 1
		else:
			flip -= 1
		if flip < 0:
			min_moves += 1
			flip = 0
	print(min_moves)
	t -= 1


from collections import deque
t = int(input())
while t:
	c = 0
	n = int(input())
	s = input()
	e = deque()
	for x in s:
		if x == '(':
			e.append(x)
		if x == ')':
			if e:
				e.pop()
			else:
				c += 1
	print(c)
	t -= 1


t = int(input())

class Dequeu:

	def __init__(self):
		self.data = []

	def push_front(self, v):
		self.data = [v] + self.data

	def push_end(self, v):
		self.data.append(v)

	def last(self):
		if not self.data:
			return None
		return self.data[-1]

	def pop(self):
		if not self.data:
			return None
		v = self.data[-1]
		self.data = self.data[:-1]
		return v
q = {'('}
for i in range(t):
	n = int(input())
	s = input()
	d = Dequeu()
	k = 0
	for c in s:
		if c == '(':
			d.push_end(c)
		elif d.last() == '(':
			d.pop()
		else:
			k += 1
	print(k)


from collections import defaultdict as dd
from math import log

def solve():
	n = int(input())
	s = list(input())
	l = ['$']
	for i in s:
		if l[-1] == '(' and i == ')':
			l.pop()
		else:
			l.append(i)
	print((len(l) - 1) // 2)
t = 1
t = int(input())
for _ in range(t):
	solve()


for _ in range(int(input())):
	am = int(input())
	data = list(input())
	w = 0
	m = 0
	for i in range(am):
		if data[i] == '(':
			w += 1
		else:
			w -= 1
		m = min(w, m)
	print(m * -1)


t = int(input())
for i in range(0, t):
	n = int(input())
	s = input()
	p = [0] * (n + 1)
	for j in range(0, n):
		if s[j] == '(':
			p[j + 1] = p[j] + 1
		else:
			p[j + 1] = p[j] - 1
	print(-min(p))


def solve():
	n = int(input())
	s = input()
	stack = []
	openindex = []
	closeindex = []
	for (i, c) in enumerate(s):
		if c == '(':
			stack.append(c)
			openindex.append(i)
		elif len(stack) == 0:
			closeindex.append(i)
		else:
			stack.pop()
			openindex.pop()
	return len(closeindex)
T = int(input())
for case in range(T):
	print(solve())


t = int(input())
for k in range(t):
	n = int(input())
	s = input()
	s = list(s)
	c = 0
	r = 0
	for i in range(0, n, 1):
		f = 0
		if s[i] == '(':
			f = 1
			c += 1
		if f != 1 and s[i] == ')' and (c > 0):
			f = 1
			c -= 1
		if f != 1 and s[i] == ')' and (c <= 0):
			r += 1
	print(r)


t = int(input())
for _ in range(t):
	input()
	s = input()
	open_brackets = 0
	wrong_brackets = 0
	for i in s:
		if i == '(':
			open_brackets += 1
		elif open_brackets >= 1:
			open_brackets -= 1
		else:
			wrong_brackets += 1
	print(wrong_brackets)


n = int(input())
result = []
for i in range(n):
	num = int(input())
	str = input()
	count = 0
	move = 0
	for c in str:
		if c == '(':
			count += 1
		elif c == ')':
			count -= 1
		if count < 0:
			move += 1
			count = 0
	result.append(move)
for i in result:
	print(i)


import sys

def get_string():
	return sys.stdin.readline().strip()

def main(s):
	stack = []
	cnt = 0
	for c in s:
		if c == '(':
			stack.append(c)
		elif stack:
			stack.pop()
		else:
			cnt += 1
	print(cnt)
N = int(input())
for i in range(N):
	size = int(input())
	s = get_string()
	main(s)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt1 = 0
	cnt2 = 0
	for i in range(n):
		if s[i] == '(':
			cnt1 += 1
		elif cnt1 == 0:
			cnt2 += 1
		else:
			cnt1 -= 1
	print(cnt1)


for j in range(int(input())):
	a = int(input())
	b = input()
	count = 0
	tot = 0
	for i in b:
		if i == '(':
			tot += 1
		if i == ')':
			tot -= 1
		if tot == -1:
			count += 1
			tot = 0
	print(count)


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
N = 10 ** 10 + 7
for _ in range(I()):
	cnt = 0
	r = 0
	n = I()
	for i in S():
		if i == ')':
			r += 1
		else:
			r -= 1
		if r > 0:
			cnt += r
			r = 0
	print(cnt)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(input())
	(o, c) = (0, 0)
	for j in range(n):
		if a[j] == '(':
			o += 1
		elif o != 0:
			o -= 1
		else:
			c += 1
	print(min(o, c))


import sys
for _ in range(int(sys.stdin.readline().rstrip())):
	n = int(sys.stdin.readline().rstrip())
	s = sys.stdin.readline().rstrip()
	re = 0
	pair = 0
	for i in s:
		if i == '(':
			pair += 1
		elif i == ')':
			if pair == 0:
				re += 1
			else:
				pair -= 1
	print(re)


from sys import stdin

def inp():
	return stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	s = inp()
	opened = 0
	closed = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			opened += 1
		else:
			closed += 1
		if closed > opened:
			ans += 1
			opened += 1
	print(ans)


def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()
for i in range(n):
	p = inp()
	s = insr()
	open = 0
	ind = 0
	move = 0
	for x in s:
		if x == ')' and open < 1:
			move += 1
		elif x == '(':
			open += 1
		else:
			open -= 1
	print(move)


for t in range(int(input())):
	n = int(input())
	l = [str(k) for k in input()]
	c = 0
	cc = 0
	for h in l:
		if h == '(':
			c += 1
		elif h == ')' and c > 0:
			c -= 1
		else:
			cc += 1
	print(cc)


t = int(input())
for j in range(t):
	n = int(input())
	stri = list(input())
	stack = []
	ct = 0
	for j in stri:
		if j == '(':
			stack.append('(')
		elif '(' in stack and stack[-1] == '(':
			stack.remove(stack[-1])
		else:
			ct += 1
	print(ct)


t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	s = input()
	is_open = 0
	count = 0
	for char in s:
		if char == '(':
			is_open += 1
		elif char == ')':
			if is_open == 0:
				count += 1
			else:
				is_open -= 1
	print(count)


def main(s):
	n = len(s)
	tmp = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			tmp += 1
		else:
			tmp -= 1
		ans = max(ans, tmp)
	print(ans)
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	main(s)


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	prev = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			ans += 1
			c = 0
	print(ans)


t = int(input())
for ij in range(t):
	n = int(input())
	s = input()
	stack = []
	for i in range(len(s)):
		if s[i] == '(':
			stack.append('(')
		elif len(stack) > 0 and stack[-1] == '(':
			stack.pop()
	print(len(stack))


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		s = str(input())
		x = 0
		ans = 0
		for i in s:
			if i == '(':
				x += 1
			else:
				x -= 1
			if x < 0:
				ans += 1
				x = 0
		print(ans)
main()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def fi():
	return float(input())

def si():
	return input()

def msi():
	return map(str, input().split())

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
from math import log, log2, sqrt, factorial, cos, tan, sin, radians, ceil, floor
import bisect
from decimal import *
abc = 'abcdefghijklmnopqrstuvwxyz'
pi = 3.141592653589793

def main():
	for _ in range(ii()):
		n = ii()
		s = si()
		l = []
		ans = 0
		for i in range(n):
			if s[i] == '(':
				l.append(1)
			else:
				l.append(-1)
		s = 0
		p = []
		for i in range(n):
			s += l[i]
			p.append(s)
		ans = min(p)
		ans *= -1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import Counter, defaultdict
BS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def to_base(s, b):
	res = ''
	while s:
		res += BS[s % b]
		s //= b
	return res[::-1] or '0'
alpha = 'abcdefghijklmnopqrstuvwxyz'
from math import floor, ceil, pi
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919]

def primef(n, plst=[]):
	if n == 1:
		return plst
	else:
		for m in primes:
			if n % m == 0:
				return primef(n // m, plst + [m])
		return primef(1, plst + [n])

def lmii():
	return list(map(int, input().split()))

def ii():
	return int(input())

def countOverlapping(string, sub):
	count = start = 0
	while True:
		start = string.find(sub, start) + 1
		if start > 0:
			count += 1
		else:
			return count
t = ii()
for i in range(t):
	n = int(input())
	s = list(input())
	while '()' in ''.join(s):
		s = list(''.join(s).replace('()', '', 1))
	seen = 0
	pos = 0
	c = 0
	while pos < len(s):
		seen += 1 if s[pos] == '(' else 0
		if 2 * seen == len(s):
			break
		if s[pos] == ')' and seen * 2 < len(s):
			s.append(s.pop(pos))
			c += 1
		else:
			pos += 1
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	open = 0
	close = 0
	count = 0
	for i in s:
		if i == '(':
			open += 1
		elif i == ')':
			close += 1
			if close > open:
				count += 1
				close = 0
				open = 0
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip()
	c = 0
	l = n // 2
	r = n // 2
	for i in range(n):
		if s[i] == '(':
			l -= 1
		elif s[i] == ')' and r <= l:
			c += 1
		elif s[i] == ')':
			r -= 1
	print(c)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(c1, c2) = (0, 0)
	i = 0
	cnt = 0
	while i < len(s):
		if s[i] == '(':
			c1 += 1
		elif s[i] == ')':
			c2 += 1
		if c2 > c1:
			r = s[:i] + s[i + 1:] + s[i]
			cnt += 1
			s = r
			c2 -= 1
			continue
		i += 1
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	a = input()
	minn = 0
	s = 0
	for i in range(n):
		if a[i] == '(':
			s += 1
		else:
			s -= 1
			if s < 0 and s < minn:
				minn = s
	print(abs(minn))


def order_brackets(s):
	opening = 0
	closing = 0
	nano = 0
	for i in s:
		if i == ')':
			if opening > 0:
				opening -= 1
			else:
				closing += 1
		else:
			opening += 1
	print(opening)
t = int(input())
for i in range(t):
	n = input()
	s = input()
	order_brackets(s)


t = int(input())
while t:
	t = t - 1
	l = input()
	x = str(input())
	op = 0
	cl = 0
	for i in list(x):
		if i == '(':
			op = op + 1
		if i == ')':
			if op == 0:
				cl = cl + 1
			else:
				op = op - 1
	print(cl)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	stack = []
	store = []
	for i in s:
		if i == '(':
			stack.append(i)
		elif len(stack) == 0:
			store.append(i)
		else:
			stack.pop()
	print(len(store))


for _ in range(int(input())):
	n = int(input())
	s = input()
	o = 0
	c = 0
	for i in range(n):
		if s[i] == '(':
			o += 1
		elif s[i] == ')':
			if o > 0:
				o -= 1
			else:
				c += 1
	if o > 0:
		c += o
	print(c // 2)


for test_i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	(l, r) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			l += 1
		else:
			r += 1
		if r > l:
			ans += 1
			r -= 1
	print(ans)


t = int(input())
for o in range(t):
	l = int(input())
	s = input().strip()
	c = 0
	counter = 0
	for ca in s:
		if ca == '(':
			counter += 1
		else:
			counter -= 1
		if counter < 0:
			counter += 1
			c += 1
	print(c)


def find(s, n):
	c = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		elif c > 0:
			c -= 1
	return c
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(find(s, n))


def main(n, s):
	cnt = 0
	ans = 0
	for i in s:
		if i == '(':
			cnt += 1
		elif cnt > 0:
			cnt -= 1
		else:
			ans += 1
	print(ans)
test = int(input())
while test:
	n = int(input())
	s = input()
	test -= 1
	main(n, s)


from math import *

def _in():
	return [int(x) for x in input().split(' ')]
tt = int(input())
for _ in range(tt):
	n = int(input())
	s = input()
	(cnt, ans) = (0, 0)
	for i in s:
		cnt = cnt + (-1 if i == ')' else 1)
		if cnt < 0:
			ans = ans + 1
			cnt = 0
	print(ans)


import math
for _ in range(int(input())):
	n = int(input())
	string = input()
	s = []
	c = 0
	for b in string:
		if b == '(':
			s.append(b)
		elif len(s) == 0:
			c += 1
		else:
			s.pop()
	print(c)


t = int(input())
for x in range(t):
	n = int(input())
	s = input()
	opened = []
	count = 0
	for br in s:
		if br == '(':
			opened.append('(')
		elif len(opened) > 0:
			opened.pop()
		else:
			count += 1
	count += len(opened)
	print(count // 2)


n = int(input())
for i in range(n):
	l = int(input())
	s = input()
	(start, end, count) = (0, 0, 0)
	for j in range(l):
		if s[j] == '(':
			start += 1
		if s[j] == ')':
			end += 1
			if start < end - count:
				count += 1
	print(count)


import math

def shrey():
	n = int(input())
	s = input()
	s = list(s)
	d = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			d += 1
		else:
			d -= 1
			if d < 0:
				d = 0
				ans += 1
	print(ans)
T = int(input())
for q in range(1, T + 1):
	shrey()


for i in range(int(input())):
	n = int(input())
	st = input()
	while st.find('()') != -1:
		st = st.replace('()', '')
	print(len(st) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	stack = []
	for i in s:
		if i == '(':
			stack.append(i)
		elif stack:
			stack.pop()
	print(len(stack))


for nt in range(int(input())):
	n = int(input())
	s = input()
	n_open = 0
	n_close = 0
	moves = 0
	for i in range(n):
		if s[i] == '(':
			n_open += 1
		if s[i] == ')':
			n_close += 1
			if n_close > n_open:
				n_close -= 1
				moves += 1
	print(moves)


def find(s):
	while s.find('()') != -1:
		s = s.replace('()', '')
	i = len(s) // 2
	return i
t = int(input())
ans = []
while t > 0:
	n = int(input())
	s = input()
	print(find(s))
	t -= 1


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	k = 0
	a = 0
	for i in range(n):
		if s[i] == '(':
			k += 1
		elif k > 0:
			k -= 1
		else:
			a += 1
	print(a)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	move = 0
	count = 0
	for i in range(n):
		if s[i] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			count += 1
			move += 1
	print(move)


from collections import deque
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from bisect import bisect_left as bl
from math import log2, ceil
from itertools import permutations

def main():
	for t in range(int(input())):
		n = int(input())
		s = input()
		o = 0
		c = 0
		omx = 0
		cmx = 0
		for i in range(n):
			if s[i] == ')':
				c += 1
				omx = max(c - o, omx)
			else:
				o += 1
		o = 0
		c = 0
		for i in range(n - 1, -1, -1):
			if s[i] == '(':
				o += 1
				cmx = max(o - c, cmx)
			else:
				c += 1
		print(max(omx, cmx))
main()


tests = int(input())
for _ in range(tests):
	n = int(input())
	s = str(input())
	open1 = 0
	close = 0
	t = 0
	for i in range(n):
		if close > open1:
			t += 1
			open1 += 1
		if s[i] == ')':
			close += 1
		else:
			open1 += 1
	print(t)


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write
mp = lambda : list(map(int, cin().split()))
(t,) = mp()
for _ in range(t):
	(n,) = mp()
	s = cin()[:-1]
	l = []
	for i in range(n):
		if s[i] == '(':
			l += [s[i]]
		elif l:
			l.remove(l[-1])
	cout(str(len(l)) + '\n')


i = input()
for k in range(int(i)):
	n = int(input())
	s = input()
	m = 0
	ma = 0
	for j in s:
		m += 1 if j == '(' else -1
		if -m > ma:
			ma = abs(m)
	print(ma)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for _ in range(testCases):
	n = int(input())
	s = input()
	arr = [1 if i == '(' else -1 for i in s]
	pre_sum = [0]
	for a in arr:
		pre_sum.append(a + pre_sum[-1])
	mini = min(pre_sum)
	ans = -mini
	answers.append(ans)
print(*answers, sep='\n')


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 1
	while cnt:
		cnt = s.count('()')
		s = s.replace('()', '')
	print(len(s) // 2)


def min_moves(n, s):
	count = 0
	ope = []
	end = []
	for x in range(len(s)):
		if s[x] == '(':
			ope.append(x)
		elif s[x] == ')':
			if len(ope) != 0:
				pair = ope.pop()
				count += 2
	return (n - count) // 2
t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	print(min_moves(n, s))


t = int(input())
for i in range(t):
	l = int(input())
	s = input()
	(ob, cb) = ([None], [None])
	for j in range(l):
		if s[j] == '(':
			ob.append('(')
		elif ob[-1] == '(':
			ob.pop()
		else:
			cb.append(')')
	print(len(cb) - 1)


def main():
	for _ in range(int(input())):
		n = int(input())
		s = list(input())
		(o, e, move, state, c, m) = (0, 0, 0, 0, 0, 0)
		for i in range(n):
			if s[i] == '(':
				o += 1
				state += 1
			else:
				e += 1
				state -= 1
			if e > o and m < e - o:
				c = e - o
				m = e - o
		print(c)
main()


for i in range(int(input())):
	n = int(input())
	a = input()
	c = 0
	t = 0
	for j in a:
		if j == '(':
			t = t + 1
		elif j == ')':
			t = t - 1
		if t < 0:
			c = c + 1
			t = 0
	print(c)


from fractions import gcd
from itertools import combinations, permutations, accumulate
from collections import deque, defaultdict, Counter
import decimal
import re
import sys
sys.setrecursionlimit(10000000)
mod = 10 ** 9 + 7

def readInts():
	return list(map(int, input().split()))

def I():
	return int(input())
for _ in range(I()):
	n = I()
	left = 0
	right = 0
	cnt = 0
	S = input()
	for i in range(len(S)):
		if S[i] == ')':
			if right >= 1:
				right -= 1
			else:
				left += 1
		else:
			right += 1
			if left > 0:
				left -= 1
				cnt += 1
	print(cnt)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ans = 0
	left = 0
	for j in range(n):
		if s[j] == '(':
			left += 1
		else:
			left -= 1
		if left < 0:
			ans += 1
			left = 0
	print(ans)


from collections import deque

def f(s):
	d1 = deque(s)
	n1 = len(d1)
	d2 = []
	a1 = d1.popleft()
	a2 = d1.popleft()
	while True:
		if a1 + a2 == '()':
			if len(d1) >= 2:
				a1 = d1.popleft()
				a2 = d1.popleft()
			elif len(d1) == 1:
				d2.append(d1.popleft())
			else:
				pass
		else:
			d2.append(a1)
			(a1, a2) = (a2, d1.popleft())
		if not d1:
			break
	if a1 + a2 != '()':
		d2.append(a1)
		d2.append(a2)
	if n1 == len(d2):
		raise Exception
	else:
		return d2

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		while True:
			try:
				s = f(s)
			except Exception:
				break
		print(len(s) // 2)
main()


def solve(s, ans):
	n = len(s)
	stack = []
	good = 0
	for i in s:
		if i == '(':
			stack.append('(')
		elif stack:
			stack.pop()
			good += 1
	moves = (n - 2 * good) // 2
	ans.append(moves)

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		s = input()
		solve(s, ans)
	for i in ans:
		print(i)
main()


def remoure(tira):
	igual = False
	i = 0
	while len(tira) != 0 and igual is False:
		tira2 = tira
		i = 0
		while i < len(tira) - 1:
			if tira[i] == '(' and tira[i + 1] == ')':
				del tira[i]
				del tira[i]
				i = 0
			else:
				i = i + 1
		if tira2 == tira:
			igual = True
	return tira

def moviment(tira):
	trobat = False
	i = 0
	com = 0
	while i < len(tira) - 1 and trobat is False:
		if tira[i] == ')' and tira[i + 1] == '(':
			del tira[i]
			tira.append(')')
			com = 1
			trobat = True
		i = i + 1
	return (tira, com)
casos = int(input())
compt_tot = []
for kk in range(casos):
	n = int(input())
	llista = list(input())
	compt = 0
	while len(llista) != 0:
		llista = remoure(llista)
		resultat = moviment(llista)
		llista = resultat[0]
		compt += resultat[1]
	compt_tot.append(compt)
for i in range(casos):
	print(compt_tot[i])


import sys

def rl():
	return sys.stdin.readline().strip()
T = int(rl())
for test in range(T):
	n = int(rl())
	s = rl()
	while s.replace('()', '') != s:
		s = s.replace('()', '')
	if len(s) == 0:
		print(0)
	else:
		closecount = 0
		opencount = 0
		index = 0
		while s[index] == ')':
			closecount += 1
			index += 1
		index = -1
		while s[index] == '(':
			opencount += 1
			index -= 1
		print(len(s) - max(closecount, opencount))


from sys import stdin

def iinput():
	return int(stdin.readline())

def sinput():
	return input()

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
t = iinput()
while t:
	t -= 1
	n = iinput()
	s = sinput()
	c = 0
	stack = []
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif stack:
			stack.pop()
		else:
			c += 1
	print(c)


r = 0
s = int(input())
for i in range(s):
	n = int(input())
	k = input()
	r = 0
	t = 0
	z = float('inf')
	for j in k:
		if j == ')':
			t = t - 1
		else:
			t = t + 1
		if t < 0 and t < z:
			z = min(z, t)
			r = r + 1
	print(r)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	incb = 0
	openb = 0
	for i in range(n):
		if s[i] == '(':
			openb += 1
		elif s[i] == ')':
			if openb == 0:
				incb += 1
			else:
				openb = openb - 1
	print(min(incb, openb))


import math
for w in range(int(input())):
	n = int(input())
	cont = 0
	neg = 0
	for i in list(input()):
		if cont < 0:
			neg += 1
			cont += 1
		if i == '(':
			cont += 1
		else:
			cont -= 1
	print(neg)


import math as mt
import sys, string
input = sys.stdin.readline
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
from collections import defaultdict
t = I()
for _ in range(t):
	n = I()
	s = input().strip()
	p = 0
	ans = 10 ** 10
	for i in range(n):
		if s[i] == ')':
			p -= 1
			ans = min(ans, p)
		else:
			p += 1
			ans = min(ans, p)
	print(-ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	a = s[0]
	b = []
	count = 0
	for i in range(len(s)):
		if s[i] == ')' and '(' not in b:
			count = count + 1
			b.append(')')
		elif s[i] == ')' and '(' in b:
			b.remove('(')
			count = count - 1
		elif s[i] == '(':
			b.append('(')
	print(len(b) // 2)


import sys
input = sys.stdin.readline
out = sys.stdout

def main():
	q = int(input())
	for i in range(q):
		n = int(input())
		s = input()
		opened = 0
		answer = 0
		for i in range(n):
			if s[i] == '(':
				opened += 1
			elif s[i] == ')' and (not opened):
				answer += 1
			else:
				opened -= 1
		print(answer)
main()


from collections import deque

def result(st):
	stack = deque()
	for x in st:
		if x == '(':
			stack.append(x)
		elif len(stack) == 0:
			stack.append(x)
		elif stack[-1] == '(':
			stack.pop()
		else:
			stack.append(x)
	return len(stack) // 2
t = int(input())
for i in range(t):
	n = int(input())
	st = input()
	print(result(st))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = 0
	a = []
	var = 0
	var1 = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
			var += var1
			var += 1
			a.append(s[i])
		elif c != 0 and a[-1] == '(':
			a.pop()
			var += 1
			var1 = 0
			c -= 1
		else:
			a.append(s[i])
	print(len(a) // 2)


t = int(input())
for _ in range(t):
	input()
	s = input()
	acc = 0
	min_acc = 0
	for c in s:
		if c == '(':
			acc += 1
		elif c == ')':
			acc -= 1
			min_acc = min(acc, min_acc)
	answer = abs(min_acc)
	print(answer)


t = int(input())
otvet = []
for _ in range(t):
	kol_zakr = 0
	kol_otkr = 0
	kol = 0
	n = int(input())
	s = input()
	for j in range(n):
		if s[j] == '(':
			kol_otkr += 1
		else:
			kol_zakr += 1
		if kol_otkr - kol_zakr < 0:
			kol += 1
			kol_zakr = 0
			kol_otkr = 0
	otvet.append(kol)
for i in range(t):
	print(otvet[i])


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	S = input().strip()
	MIN = 0
	NOW = 0
	for s in S:
		if s == '(':
			NOW += 1
		else:
			NOW -= 1
			MIN = min(NOW, MIN)
	print(-MIN)


for iota in range(int(input())):
	n = int(input())
	x = list(input())
	ans = 0
	count = 0
	for i in x:
		if i == '(':
			ans += 1
		else:
			ans -= 1
		if ans < 0:
			ans = 0
			count += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	k = 0
	while n:
		a = s.index('(')
		if s[a + 1:].count(')'):
			b = s[a + 1:].index(')') + a + 1
			x = s.pop(a)
			y = s.pop(b - 1)
		else:
			b = s[:a].index(')')
			x = s.pop(a)
			y = s.pop(b)
			k += 1
		n -= 2
	print(k)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = list(input())
	p = []
	out = []
	c = 0
	for i in s:
		if i == '(':
			p.append(i)
		elif len(p) == 0:
			c += 1
			out.append(i)
		elif p[len(p) - 1] == '(':
			p.pop()
	print(c)


import math
import sys
import os
for _ in range(int(input())):
	n = int(input())
	s = input()
	(f, c) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			f += 1
		else:
			f -= 1
			if f == -1:
				c += 1
				f = 0
	print(c)


from sys import stdin, stdout
from collections import deque

def main():
	for _ in range(int(stdin.readline())):
		n = int(input())
		st = input()
		stack = []
		for i in range(n):
			if st[i] == ')':
				if len(stack) != 0 and stack[-1] == '(':
					stack.pop()
				else:
					stack.append(')')
			else:
				stack.append('(')
		print(len(stack) // 2)
main()


from sys import stdin, stdout
input = lambda : stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	a = input()
	lst = []
	nd = 0
	for i in a:
		if i == '(':
			lst.append(i)
		else:
			try:
				lst.pop()
			except:
				nd += 1
	print(nd)


for i in range(int(input())):
	n = int(input())
	s = input()
	ctr = 0
	for j in range(n):
		if s[j] == '(':
			ctr += 1
		elif s[j] == ')' and ctr > 0:
			ctr -= 1
	print(ctr)


from sys import stdin, stdout
INF = 100000000000.0

def get_int():
	return int(stdin.readline().strip())

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_array():
	return list(map(int, stdin.readline().strip().split()))

def get_string():
	return stdin.readline().strip()
for _ in range(int(stdin.readline())):
	n = get_int()
	s = get_string()
	ar = [c for c in s]
	f1 = 0
	ans = 0
	i = 0
	while i < n:
		if ar[i] == '(':
			f1 += 1
		if ar[i] == ')':
			if f1 == 0:
				ar.pop(i)
				i -= 1
				ar.append(')')
				ans += 1
			else:
				f1 -= 1
		i += 1
	print(ans)


import sys
input = lambda : sys.stdin.readline().strip()
t = int(input())

def check(s):
	o = 0
	for i in s:
		if i == '(':
			o += 1
		else:
			o -= 1
		if o < 0:
			return True
	return False
while t:
	t -= 1
	n = int(input())
	s = list(input())
	ans = 0
	st = []
	for i in range(n):
		if s[i] == '(':
			st.append(i)
		elif len(st) and s[st[-1]] == '(':
			st.pop()
	print(len(st))


for i in range(int(input())):
	n = int(input())
	s = input()
	pair = 0
	step = 0
	for j in s:
		if pair >= 0 and j == ')':
			step += 1
		elif pair < 0 and j == ')':
			pair += 1
		else:
			pair -= 1
	print(step)


for i in range(int(input())):
	length = int(input())
	sequence = input()
	of = [0, 0, 0]
	for i in sequence:
		if i == '(':
			of[0] += 1
		elif i == ')':
			of[1] += 1
			if of[1] > of[0]:
				of[1] -= 1
				of[2] += 1
	print(abs(of[2]))


def is_correct(brackets):
	level = 0
	for bracket in brackets:
		if bracket == '(':
			level += 1
		elif bracket == ')':
			level -= 1
		if level < 0:
			return False
	return True

def correct_one(brackets):
	level = 0
	for (i, bracket) in enumerate(brackets):
		if bracket == '(':
			level += 1
		elif bracket == ')':
			level -= 1
		if level < 0:
			del brackets[i]
			brackets.append(')')
			return brackets
N = int(input())
for _ in range(N):
	M = int(input())
	brackets = list(input())
	corrections = 0
	while not is_correct(brackets):
		brackets = correct_one(brackets)
		corrections += 1
	print(corrections)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(c1, c2) = (0, 0)
	ans = 0
	for (i, x) in enumerate(s):
		if x == '(':
			c1 += 1
		else:
			c1 -= 1
		ans = min(c1, ans)
	print(-ans)


def countTime(s):
	while '()' in s:
		s = s.replace('()', '')
	return len(s) // 2
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	ans.append(countTime(s))
for i in ans:
	print(i)


t = int(input())
while t:
	n = int(input())
	s = input()
	stack = []
	c = 0
	for i in s:
		if i == ')':
			if stack == [] or stack[-1] == ')':
				c += 1
				stack.append(i)
			elif stack != [] and stack[-1] == '(':
				stack.pop()
		else:
			stack.append(i)
	print(c)
	t -= 1


def solve(string):
	s = []
	for c in string:
		if c == ')':
			if len(s) > 0 and s[-1] == '(':
				s.pop()
			else:
				s.append(')')
		else:
			s.append('(')
	return len(s) // 2
for t in range(int(input())):
	N = int(input())
	print(solve(input()))


x = int(input())
odg = []
for i in range(0, x):
	n = int(input())
	l = input()
	l1 = l
	l2 = l
	while True:
		l1 = l1.replace('()', '')
		if l1 == l2:
			break
		else:
			l2 = l1
	odg.append(int(len(l1) / 2))
for e in odg:
	print(e)


strings_counter = int(input())
strings = []
for i in range(strings_counter):
	string_len = int(input())
	string = input()
	strings.append((string_len, string))
for data in strings:
	string_len = data[0]
	string = list(data[1])
	stack = []
	for i in range(len(string)):
		stack.append(string[i])
		if len(stack) >= 2 and (stack[len(stack) - 1] == ')' and stack[len(stack) - 2] == '('):
			stack.pop()
			stack.pop()
	answer = int(len(stack) / 2)
	print(answer)


a = int(input())
for i in range(a):
	b = int(input())
	c = input()
	for i in c:
		if c.find('()') == -1:
			break
		c = c.replace('()', '')
	print(len(c) // 2)


import sys
import math

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		pre = 0
		post = 0
		s = input()
		for i in s:
			if i == '(':
				pre += 1
			elif pre > 0:
				pre -= 1
			else:
				post += 1
		print(pre)
main()


class Stack:
	stack = []
	top = -1

	def push(self, element):
		self.top += 1
		self.stack.insert(self.top, element)

	def pop(self):
		self.top -= 1
t = int(input())
for z in range(t):
	n = int(input())
	brackets = input()
	s = Stack()
	for i in brackets:
		if i == '(':
			s.push(i)
		elif i == ')' and s.top > -1:
			s.pop()
	print(s.top + 1)


def check(l):
	evens = 0
	odds = 0
	for i in l:
		if i == '(':
			evens += 1
		else:
			odds += 1
		if odds > evens:
			return False
	return True

def findBadBrack(l):
	evens = 0
	odds = 0
	for i in range(len(l) - 1, -1, -1):
		if l[i] == '(':
			evens += 1
		else:
			odds += 1
		if evens > odds:
			return i
t = int(input())
for _ in range(t):
	crap = input()
	seq = list(input())
	count = 0
	while not check(seq):
		index = findBadBrack(seq)
		seq.pop(index)
		seq.insert(0, '(')
		count += 1
	print(count)


for i in range(int(input())):
	input()
	s = input()
	(b, r) = (0, 0)
	for c in s:
		b += 1 if c == '(' else -1
		if b < 0:
			r += 1
			b = 0
	print(r)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ans = 0
	count = 0
	for i in s:
		if i == ')':
			count -= 1
		else:
			count += 1
		if count < ans:
			ans = count
	print(abs(ans))


def factor(n):
	f = {}
	while n % 2 == 0:
		f[2] = f.get(2, 0) + 1
		n /= 2
	d = 3
	while d * d <= n:
		while n % d == 0:
			f[d] = f.get(d, 0) + 1
			n /= d
		d += 2
	if n > 1:
		f[n] = f.get(n, 0) + 1
	return f
n = int(input())
for i in range(0, n):
	y = int(input())
	x = str(input())
	z = list(x)
	count = 0
	for j in range(0, y):
		if z[j] == '(':
			for k in range(min(j + 1, y), y):
				if z[k] == ')':
					z[k] = '@'
					break
	for j in range(0, y):
		if z[j] == ')':
			count += 1
	print(count)


from collections import defaultdict
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	l = list(input())
	res = []
	for i in range(n):
		if l[i] == '(':
			res.append('(')
		elif len(res) > 0 and res[-1] == '(':
			res.pop()
		else:
			res.append(')')
	print(len(res) // 2)


c = int(input())
for i in range(c):
	cont = 0
	foo = input()
	cad = input()
	while '()' in cad:
		cont += 1
		cad = cad.replace('()', '')
	print(cad.count(')'))


for _ in range(int(input())):
	sk = []
	n = int(input())
	s = list(input())
	c = 0
	for i in s:
		if i == '(':
			sk.append(i)
		elif sk == [] and i == '(':
			sk.append(i)
		elif sk == [] and i == ')':
			c = c + 1
		else:
			sk.pop()
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input('')
	k = ''
	l = []
	while True:
		l.append(s)
		if '()' in s:
			s = s.replace('()', '')
		if s in l:
			break
	print(len(s) // 2)


t = int(input())
result = []
for i in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	ans = s.count(')')
	result.append(ans)
for i in result:
	print(i)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	f = 0
	r = 0
	ans = 0
	for i in s:
		if i == '(':
			f += 1
		elif f > 0:
			f -= 1
		else:
			r += 1
	print(f)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for j in range(n):
		if s[j] == '(':
			c += 1
		else:
			c -= 1
		ans = min(ans, c)
	print(abs(ans))


t = int(input())
for i in range(t):
	stk = []
	n = int(input())
	s = input()
	for i in s:
		if len(stk) != 0:
			if stk[-1] == '(' and i == ')':
				stk.pop()
			else:
				stk.append(i)
		else:
			stk.append(i)
	print(len(stk) // 2)


for s in [*open(0)][2::2]:
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	n = iinput()
	a = input()
	stk = ['#']
	for i in a:
		if i == '(':
			stk.append('(')
		elif stk[-1] == '(':
			stk.pop()
		else:
			stk.append(')')
	stk.remove('#')
	print(min(stk.count('('), stk.count(')')))


for _ in range(int(input())):
	nn = int(input())
	n = input()
	bal = 0
	ans = 0
	for i in n:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				ans += 1
				bal = 0
	print(ans)


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
from bisect import bisect, bisect_right, bisect_left

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def solve():
	n = get_int()
	st = input()
	(c, ans) = (0, 0)
	for val in st:
		if val == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			c = 0
			ans += 1
	return ans

def main():
	print(solve())
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	a = []
	b = []
	for i in range(n):
		if s[i] == '(':
			a.append(i)
		else:
			b.append(i)
	vis = [0] * len(b)
	lb = len(b)
	j = 0
	ask = 0
	for i in range(len(a)):
		while j < lb:
			if b[j] > a[i] and vis[j] == 0:
				vis[j] = 1
				j += 1
				ask += 1
				break
			else:
				j += 1
	print((n - 2 * ask) // 2)


def check(bruh):
	tmp = 0
	for i in range(0, len(bruh)):
		if bra[i] == ')':
			tmp += -1
		elif bra[i] == '(':
			tmp += 1
		if tmp < 0:
			return 0
	return 1
t = int(input())
for _ in range(0, t):
	n = int(input())
	bra = input()
	result = 0
	while 1:
		if check(bra) == 1:
			break
		else:
			bb = bra.find(')')
			bra = bra[0:bb] + bra[bb + 1:]
			bra = bra + ')'
			result += 1
	print(result)


sss = []
for _ in range(int(input())):
	n = int(input())
	s = input()
	cmax = 0
	for i in s:
		if i == '(':
			cmax += 1
		elif cmax > 0:
			cmax -= 1
	print(cmax)
	sss.append(cmax)


import sys, math, os
from io import BytesIO, IOBase
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 9
mod = 998244353
for t in range(int(data())):
	n = int(data())
	s = data()
	cnt = 0
	a = 0
	for i in s:
		if i == '(':
			a += 1
		else:
			a -= 1
		if a < 0:
			cnt += 1
			a = 0
	out(a)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = input()
	open = 0
	close = 0
	count = 0
	for ch in arr:
		if ch == '(':
			open += 1
		else:
			close += 1
		if close > open:
			close -= 1
			count += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(opens, close) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			opens += 1
		elif opens > 0:
			opens -= 1
		else:
			close += 1
	print(close)


a = int(input())
l = []
for i in range(a):
	x = int(input())
	b = str(input())
	open = 0
	close = 0
	move = 0
	for j in b:
		if j == '(':
			open += 1
			continue
		if j == ')' and open == 0:
			move += 1
			continue
		if j == ')' and open > 0:
			open -= 1
			continue
	l.append(move)
for j in l:
	print(j)


for ii in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	A = []
	for i in range(n):
		if A == [] or not (A[-1] == '(' and s[i] == ')'):
			A.append(s[i])
		else:
			A.pop()
	print(len(A) // 2)


t = int(input())
for _ in range(t):
	q = int(input())
	s = input()
	l = ['()', '{}', '[]']
	st = []
	for i in s:
		if i in '([{':
			st.append(i)
		elif len(st) != 0 and st[-1] + i in l:
			st.pop()
	print(len(st))


t = int(input())
li = []
ls = []
for i in range(t):
	ls = ls + [int(input())]
	li = li + [input()]
for i in range(t):
	a = ls[i]
	s = li[i]
	(x, y, m) = (0, 0, 0)
	for j in range(a):
		if s[j] == '(':
			x += 1
		else:
			y += 1
		if y > x:
			y -= 1
			m += 1
	print(m)


import sys
input = sys.stdin.readline

def solve(n, s):
	open_b = 0
	close_b = 0
	count = 0
	while s:
		b = s.popleft()
		if b == '(':
			open_b += 1
		else:
			close_b += 1
		if close_b > open_b:
			count += 1
			close_b -= 1
			s.append(b)
	return count
from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = deque(list(input().strip()))
	print(solve(n, s))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(input())
	dp = [0 for i in range(n)]
	stack = []
	ans = 0
	for i in range(n):
		if arr[i] == '(':
			if ans == -1:
				ans = 0
			stack.append('(')
			dp[i] = ans
		elif len(stack) == 0:
			dp[i] = -1
		else:
			stack.pop()
			ans += 2
			dp[i] = ans
			dp[i] = ans
	if max(dp) == -1:
		print(n)
	else:
		print((n - max(dp)) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	x = input()
	curr = 0
	res = 0
	for item in x:
		if item == ')':
			if curr == 0:
				res += 1
			else:
				curr -= 1
		if item == '(':
			curr += 1
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = input()
	a = '('
	aa = 0
	b = ')'
	bb = 0
	for e in s:
		if aa > 0 and e == b:
			aa -= 1
		elif e == a:
			aa += 1
	print(aa)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	openn = []
	close = []
	for i in s:
		if i == '(':
			openn.append(i)
		if i == ')' and openn == []:
			close.append(i)
		if i == ')' and openn != []:
			openn.pop()
	print(len(close))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(mm, m) = (0, 0)
	for c in s:
		if c == '(':
			m += 1
		elif c == ')':
			m -= 1
			mm = min(mm, m)
	print(abs(mm))


t = int(input())
for x in range(t):
	n = int(input())
	s = input()
	bal = 0
	ic = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				ic += 1
	print(ic)


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt1 = 0
	ans = 0
	i = 0
	for x in s:
		if x == '(':
			cnt1 += 1
		if x == ')':
			cnt1 -= 1
		if cnt1 + ans < 0:
			ans += 1
		i += 1
	print(ans)


for i in range(int(input())):
	n = int(input())
	a = input()
	ans = 0
	neg = 0
	for i in range(n):
		if a[i] == ')':
			neg -= 1
		else:
			neg += 1
		if neg < 0:
			ans += 1
			neg = 0
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	p = input()
	s = []
	r = 0
	for j in range(n):
		if p[j] == '(':
			s.append(p[j])
		elif len(s) > 0:
			s.pop()
		else:
			r += 1
	print(r)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
t = 1
t = int(input())
for _ in range(t):
	n = l()[0]
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	k1 = 0
	ans1 = 0
	for j in range(n):
		if a[j] == '(':
			k1 += 1
		if a[j] == ')':
			k1 -= 1
		if k1 < 0:
			k1 += 1
			ans1 += 1
	print(ans1)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	(l, r, o) = (0, 0, 0)
	for c in s:
		if c == '(':
			l += 1
			o += 1
		if c == ')':
			r += 1
			if o > 0:
				o -= 1
			else:
				ans += 1
	print(ans if l == r else 0)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
import datetime
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	starttime = datetime.datetime.now()
	for _ in range(int(input())):
		n = int(input())
		s = input()
		l = 0
		for i in range(len(s)):
			if s[i] == '(':
				l = i
				break
		k = 0
		c = 0
		for i in range(l, len(s)):
			if s[i] == '(':
				k += 1
			if s[i] == ')' and k > 0:
				k -= 1
				c += 1
		print(n // 2 - c)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin, stdout

class SOLVE:

	def solve(self):
		R = stdin.readline
		W = stdout.write
		ans = []
		for i in range(int(R())):
			n = int(R())
			s = R()
			seq = move = 0
			for j in range(n):
				if s[j] == '(':
					seq += 1
				else:
					seq -= 1
					if seq < 0:
						move += 1
						seq = 0
			ans.append(str(move))
		W('\n'.join(ans))

def main():
	s = SOLVE()
	s.solve()
main()


T = int(input())
while T:
	n = int(input())
	s = input()
	A = [0 for i in range(n)]
	B = [0 for i in range(n)]
	R = []
	c = 0
	for i in s:
		if i == '(':
			R.append('(')
		elif len(R) > 0 and R[-1] == '(':
			R = R[:-1]
		else:
			c = c + 1
			R.append(')')
	print(c)
	T = T - 1


test = int(input())
test_arr = []
for _ in range(test):
	n = int(input())
	s = str(input())
	count_op = 0
	count_cl = 0
	count = 0
	for i in s:
		if i == ')':
			count_cl += 1
		else:
			count_op += 1
		if count_cl > count_op:
			count += 1
			count_cl -= 1
	test_arr.append(count)
for t in test_arr:
	print(t)


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	l = list(str(s))
	curr = 0
	ans = 0
	k = []
	while l:
		if l[0] == '(':
			k.append(l.pop(0))
		elif l[0] == ')':
			if k:
				k.pop()
				l.pop(0)
			else:
				l.append(l.pop(0))
				ans += 1
	print(ans)


m = int(input())
while m:
	m -= 1
	n = int(input())
	s = input()
	l = []
	p = 0
	(ma, mi) = (0, 10000)
	for i in s:
		if i == '(':
			p += 1
		else:
			p -= 1
		l.append(p)
	c = 0
	print(-min(l))


n = int(input())
for i in range(n):
	size = int(input())
	s = input()
	direita = 0
	esquerda = 0
	erro = 0
	for bracket in s:
		if bracket == ')':
			if direita == 0:
				erro += 1
			else:
				direita -= 1
		else:
			direita += 1
	print(erro)


import time, math, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x))

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count

def readTree(v, e):
	adj = [set() for i in range(v + 1)]
	for i in range(e):
		(u1, u2, w) = IP()
		adj[u1].add((u2, w))
		adj[u2].add((u1, w))
	return adj

def dfshelper(adj, i, visited):
	nodes = 1
	visited[i] = True
	for ele in adj[i]:
		if visited[ele] == False:
			nd = dfshelper(adj, ele, visited)
			nodes += nd
	return nodes

def dfs(adj, v):
	visited = [False] * (v + 1)
	li = []
	for i in range(v):
		if visited[i] == False:
			nodes = dfshelper(adj, i, visited)
			li.append(nodes)
	return li
mx = 10 ** 9 + 7

def solve():
	n = II()
	s = input()
	li = [s[0]]
	for i in range(1, n):
		ele = s[i]
		if ele == ')':
			if li and li[-1] != '(':
				li.append(')')
			elif li and li[-1] == '(':
				li.pop()
			else:
				li.append(')')
		else:
			li.append('(')
	print(len(li) // 2)
t = int(input())
for i in range(t):
	solve()


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	n = I()
	s = input().strip()
	a = []
	for i in s:
		if len(a) == 0:
			a.append(i)
		elif i == ')' and a[-1] == '(':
			a.pop()
		else:
			a.append(i)
	print(len(a) // 2)
for _ in range(I()):
	solve()


def find_cnt():
	n = int(input())
	s = input()
	cnt = 0
	w = 0
	for i in range(len(s)):
		if s[i] == '(':
			w += 1
		elif s[i] == ')' and w > 0:
			w -= 1
			cnt += 1
	return (len(s) - cnt * 2) // 2
t = int(input())
for i in range(t):
	print(find_cnt())


for i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	cnt = 0
	for j in s:
		if j == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			ans += 1
			cnt = 0
	print(ans)


for i in range(int(input())):
	seqLen = int(input())
	seq = input()
	tally = 0
	mintally = 0
	for c in seq:
		if c == ')':
			tally -= 1
		else:
			tally += 1
		if tally < mintally:
			mintally = tally
	print(abs(mintally))


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	(ans1, ans2) = (0, 0)
	n = int(ii())
	s = ii()
	(k, m) = (0, 0)
	for i in range(n):
		if s[i] == ')':
			if k == 0:
				ans1 += 1
			else:
				k -= 1
		else:
			k += 1
	s = s[::-1]
	k = 0
	for i in range(n):
		if s[i] == '(':
			if k == 0:
				ans2 += 1
			else:
				k -= 1
		else:
			k += 1
	print(min(ans1, ans2))
	return
for t in range(int(ii())):
	solve()


t = int(input())
for i in range(t):
	l = int(input())
	s = input()
	check = 0
	for j in range(l):
		if s[j] == '(':
			check += 1
		elif check >= 1:
			check -= 1
	if check == 0:
		m = 0
	else:
		m = check
	print(m)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input().rstrip()
	(cnt1, cnt2) = (0, 0)
	ans = 0
	for x in s:
		if x == '(':
			cnt1 += 1
		else:
			cnt2 += 1
		if cnt1 >= cnt2:
			continue
		else:
			ans += 1
			cnt2 -= 1
	print(ans)


import sys
input = sys.stdin.readline
f = lambda : list(map(int, input().split()))
res = []
for _ in range(int(input())):
	n = int(input())
	inp = input()
	stack = ''
	for c in inp:
		if stack and (stack[-1] == '(' and c == ')'):
			stack = stack[:len(stack) - 1]
		else:
			stack += c
	res.append(stack.count('('))
print('\n'.join(map(str, res)))


for i in range(int(input())):
	n = int(input())
	s = input()
	counter = 0
	ans = 0
	for g in range(len(s)):
		if s[g] == '(':
			counter += 1
		else:
			counter -= 1
		if counter < ans:
			ans = counter
	print(abs(ans))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	m = s.split('()')
	temp = ''
	while True:
		s = ''
		s = s.join(m)
		m = s.split('()')
		if temp == m:
			s = s.join(m)
			break
		temp = m
	print(len(s) // 2)


T = int(input())
for _ in range(T):
	n = int(input())
	s = input()
	validity_array = [0]
	curr = 0
	for i in s:
		if i == '(':
			curr += 1
			validity_array.append(curr)
		else:
			curr -= 1
			validity_array.append(curr)
	print(-1 * min(validity_array))


T = int(input())
for i in range(1, T + 1):
	l = int(input())
	b = input()
	total = 0
	op = 0
	for i in b:
		if i == '(':
			total += 1
		else:
			total -= 1
		if total == -1:
			op += 1
			total += 1
	print(op)


t = int(input())
for i in range(t):
	no = int(input())
	l = list(str(input()))
	j = 0
	length = 0
	while j + 1 < len(l):
		if l[j] == '(' and l[j + 1] == ')':
			l.pop(j)
			l.pop(j)
			if j > 0:
				if l[j - 1] == '(' and j < len(l):
					if l[j] == ')':
						j = j - 1
		else:
			j = j + 1
	print(len(l) // 2)


from collections import deque
for t in range(int(input())):
	n = int(input())
	s = input()
	stack = deque()
	for i in range(n):
		if len(stack) == 0:
			stack.append(s[i])
			continue
		top = stack.pop()
		if top == '(' and s[i] == ')':
			continue
		else:
			stack.append(top)
			stack.append(s[i])
	print(len(stack) // 2)


for _ in range(int(input())):
	n = int(input())
	arr = input()
	arr = list(arr)
	suma = 0
	ans = 0
	for i in range(len(arr)):
		if arr[i] == '(':
			suma += 1
		elif arr[i] == ')':
			suma -= 1
			if suma < 0:
				ans += 1
				suma = 0
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	s_curr = 0
	lowest = 0
	for brac in s:
		s_curr = s_curr + (1 if brac == '(' else -1)
		lowest = min(lowest, s_curr)
	print(-lowest)


t = int(input())

def bracket_solos(linea: str) -> int:
	abiertos = 0
	for i in linea:
		if i == '(':
			abiertos += 1
		else:
			abiertos -= 1
			if abiertos < 0:
				abiertos = 0
	return abiertos
for i in range(t):
	n = int(input())
	linea = input()
	print(bracket_solos(linea))


def ans():
	n = int(input())
	x = input()
	s = []
	for i in range(n):
		if x[i] == ')':
			if len(s) == 0:
				s.append(')')
			elif s[-1] == '(':
				s = s[:-1]
			else:
				s.append(')')
		if x[i] == '(':
			s.append('(')
	print(int(len(s) / 2))
	return
t = int(input())
for i in range(t):
	ans()


from fractions import Fraction
from collections import defaultdict
import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
krish = 1000
ans = krish - 900
res = ans - 90
t = int(input())
for _ in range(t):
	n = int(input())
	st = input()
	l = list(st)
	mn = 0
	c = 0
	for i in l:
		if i == '(':
			c += 1
		else:
			c -= 1
		mn = min(mn, c)
	print(mn * -1)
	res += 1


n = int(input())
for i in range(n):
	a = int(input())
	s = input()
	b = list()
	for i in s:
		if i == '(':
			b.append(1)
		elif i == ')':
			b.append(0)
	o = 0
	c = 0
	m = 0
	for i in range(a):
		if b[i] == 0 and o == c:
			m += 1
		elif b[i] == 1:
			o += 1
		elif b[i] == 0:
			c += 1
	print(m)


t = int(input())
for _ in range(t):
	n = int(input())
	ch = input()
	(np, nq) = (0, 0)
	for i in range(n):
		if ch[i] == '(':
			np += 1
		elif np > 0:
			np -= 1
		else:
			nq += 1
	print(nq)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	delta = 0
	a = 0
	for i in s:
		if i == '(':
			delta += 1
		else:
			delta -= 1
		if delta < 0:
			a += 1
			delta = 0
	if delta > 0:
		ans = min(delta, a)
	else:
		ans = a
	print(ans)


for _ in range(int(input())):
	n = int(input())
	x = input()
	oh = 0
	ah = 0
	maxi = 0
	for i in x:
		if i == '(':
			oh += 1
		else:
			oh -= 1
			if oh < 0:
				oh = 0
				maxi += 1
	print(maxi)


n = int(input())
for _ in range(n):
	a = int(input())
	l = [i for i in input()]
	i = 0
	c = 0
	x = 0
	while i != a - 1:
		if l[i] == '(':
			c += 1
		elif c == 0:
			z = l.pop(i)
			l.append(z)
			x += 1
			i -= 1
		else:
			c -= 1
		i += 1
	print(x)


import re
bracketList = []
designs = eval(input())
for i in range(designs):
	extra = input()
	design = input()
	bracketList.append(design)
for element in bracketList:
	while True:
		if '()' in element:
			element = re.sub('\\(\\)', '', element)
		else:
			break
	print(int(len(element) / 2))


t = int(input())
for i in range(t):
	n = int(input())
	s = input().strip('\n')
	smallest = 0
	c1 = 0
	c2 = 0
	for i in range(n):
		if s[i] == '(':
			c1 += 1
		else:
			c2 += 1
		if c1 - c2 < smallest:
			smallest = c1 - c2
	print(abs(smallest))


for t in range(int(input())):
	n = int(input())
	s = input()
	(openbr, closebr) = (0, 0)
	ans = 0
	for i in range(n):
		if s[i] == '(':
			openbr += 1
		else:
			closebr += 1
		if closebr > openbr:
			ans += 1
			closebr -= 1
	print(ans)


for t in range(int(input())):
	n = int(input())
	br = list(input())
	(balance, move) = (0, 0)
	while len(br) > 0:
		ckt = br[0]
		br.pop(0)
		if ckt == '(':
			balance = balance + 1
		elif balance == 0:
			br.append(ckt)
			move = move + 1
		else:
			balance = balance - 1
	print(move)


def moveBrackets(brackets: str) -> None:
	stack = []
	cost = 0
	for char in brackets:
		if char == '(':
			stack.append('(')
		elif '(' in stack:
			index = stack.index('(')
			stack.pop(index)
		else:
			cost += 1
	return len(stack)
test_cases = int(input())
for _ in range(test_cases):
	N = int(input())
	brackets = input()
	print(moveBrackets(brackets))


def driver():
	t = int(input())
	for i in range(t):
		print(solution())

def solution():
	n = int(input())
	b = list(input())
	(o, c, i) = (0, 0, 0)
	while i < n:
		if b[i] == '(':
			o += 1
		else:
			o -= 1
		if o < 0:
			o += 1
			b = b[:i] + b[i + 1:]
			b.append(')')
			c += 1
			i -= 1
		i += 1
	return c
driver()


for i in range(int(input())):
	n = int(input())
	s = input()
	k = 0
	l = [0]
	for i in range(n):
		if s[i] == '(':
			k += 1
		else:
			k -= 1
			if k < 0:
				l.append(k)
	print(abs(min(l)))


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	x = 0
	for i in range(n):
		if s[i] == '(':
			if x < 0:
				c += abs(x)
				x = 0
			x += 1
		elif s[i] == ')':
			x -= 1
	print(c)


t = int(input())
for N in range(t):
	n = int(input())
	s = input()
	m = -1
	q = 0
	for c in s:
		if c == ')':
			q = q + 1
		else:
			q = q - 1
		if q > m:
			m = q
	print(m)


t = int(input())
for i in range(t):
	n = int(input())
	st = input()
	sy = list(st)
	countst = 0
	countend = 0
	for k in range(len(sy)):
		if sy[k] == '(':
			countst = countst + 1
		elif sy[k] == ')' and countst > 0:
			countst = countst - 1
		else:
			countend = countend + 1
	print((countend + countst) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	f = 0
	e = 0
	for i in range(n):
		if s[i] == '(':
			f += 1
		elif s[i] == ')':
			if f != 0:
				f -= 1
			else:
				e += 1
	print(e)


for _ in range(int(input())):
	n = int(input())
	s = input().rstrip()
	tmp = 0
	ans = 0
	for i in s:
		if i == '(':
			tmp += 1
		else:
			tmp -= 1
			if tmp < 0:
				tmp = 0
				ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(count, left, right) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			left += 1
		else:
			right += 1
		if right > left:
			count += 1
			(left, right) = (0, 0)
	print(count)


t = 1
t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	st = []
	ans = 0
	for i in range(n):
		if s[i] == '(':
			st.append(1)
		elif len(st):
			st.pop()
		else:
			ans += 1
	print(ans)


line = input()
t = int(line)
for j in range(t):
	line = input()
	line = input()
	(l, r, cur) = (0, 0, 0)
	for i in line:
		if i == '(':
			cur -= 1
		elif i == ')':
			cur += 1
		l = max(l, cur)
	cur = 0
	for i in reversed(line):
		if i == '(':
			cur += 1
		elif i == ')':
			cur -= 1
		r = max(r, cur)
	print(min(r, l))


def proper(s):
	c = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			return False
	return True
for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	while not proper(s):
		c = 0
		for i in range(len(s)):
			if s[i] == '(':
				c += 1
			else:
				c -= 1
			if c < 0:
				p = s[:i] + s[i + 1:] + s[i]
				s = p[:]
				ans += 1
				break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	string = input()
	openb = 0
	cnt = 0
	for i in string:
		if i == '(':
			openb += 1
		else:
			openb -= 1
		if openb < 0:
			cnt += 1
			openb += 1
	print(cnt)


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input().strip()
	tot = 0
	for i in s:
		if i == '(':
			tot += 1
		elif tot > 0 and i == ')':
			tot -= 1
	print(tot)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	open = []
	for i in range(n):
		if a[i] == '(':
			open.append(a[i])
		elif len(open) != 0:
			open.pop()
	print(len(open))


for _ in range(int(input())):
	s = int(input())
	n = list(input())
	ans = 0
	while ''.join(n).count('()') > 0:
		todel = []
		for i in range(len(n) - 1):
			if n[i] == '(' and n[i + 1] == ')':
				todel.append(i)
				todel.append(i + 1)
		for i in todel[::-1]:
			del n[i]
	if len(n) > 0:
		st = []
		end = []
		for i in range(len(n)):
			if n[i] == '(':
				st.append(i)
			else:
				end.append(i)
		end.reverse()
		while st[0] < end[0]:
			del st[0]
			del end[0]
		print(len(st))
	else:
		print(0)


def calc():
	l = int(input())
	s = str(input())
	a = []
	cnt = 0
	ans = 0
	for i in range(0, l):
		if s[i] == '(':
			cnt += 1
			a.append(cnt)
		else:
			cnt -= 1
			a.append(cnt)
	for i in range(0, l):
		if a[i] < 0:
			ans = max(ans, -a[i])
	print(ans)
t = int(input())
for i in range(1, t + 1):
	calc()


for _ in range(int(input())):
	input()
	x = input()
	opening = []
	closing = []
	for i in x:
		if i == ')':
			if len(opening) == 0:
				closing.append(')')
			else:
				opening.pop()
		else:
			opening.append('(')
	print(len(opening))


def main():
	for i in range(int(input())):
		a = int(input())
		s = ' '.join(input()).split()
		cnt = 0
		h = 1
		while h:
			h = 0
			for i in range(len(s)):
				for j in range(i + 1, len(s)):
					if s[i] == '(' and s[j] == ')':
						s[i] = '*'
						s[j] = '*'
						h = 1
						cnt += 2
						break
		print((len(s) - cnt) // 2)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	opens = 0
	abnormals = 0
	for c in s:
		if c == '(':
			opens += 1
		elif opens > 0:
			opens -= 1
		else:
			abnormals += 1
	print(str(abnormals))


s = int(input())
q22 = 0
q222 = 0
for i in range(s):
	n = int(input())
	c = input()
	for ii in c:
		if ii == ')':
			if q22 > 0:
				q22 -= 1
				q222 += 2
		elif ii == '(':
			q22 += 1
	print((n - q222) // 2)
	q222 = 0
	q22 = 0


t = int(input())
for i in range(t):
	n = int(input())
	inp = input()
	temp = 0
	cnt = 0
	for i in range(len(inp)):
		if inp[i] == '(':
			temp = temp + 1
		elif inp[i] == ')':
			temp = temp - 1
			if temp < 0:
				temp = 0
				cnt = cnt + 1
	print(cnt)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	limit = 10 ** 18
	ans = 0
	for test in range(tests):
		n = inp()
		s = insr()
		g_min = 0
		curr = 0
		for i in s:
			if i == '(':
				curr = curr + 1
			else:
				curr = curr - 1
			g_min = min(g_min, curr)
		print(abs(g_min))
main()


def sol(n, brackets):
	balance_counter = 0
	total_moves = 0
	for i in range(0, n):
		balance_counter += 1 if brackets[i] == '(' else -1
		if balance_counter < 0:
			total_moves += 1
			balance_counter = 0
	return total_moves
t = int(input())
results = list()
for i in range(0, t):
	n = int(input())
	brackets = input()
	results.append(sol(n, brackets))
for result in results:
	print(result)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count = 0
	sol = 0
	for char in s:
		if char == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			count = 0
			sol += 1
	print(sol)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	counter = 0
	mx = 0
	for c in s:
		if c == '(':
			counter -= 1
		elif c == ')':
			counter += 1
		if counter > mx:
			mx = counter
	print(mx)


def check(s):
	stack = []
	moves = 0
	for i in range(len(s)):
		if s[i] == ')':
			if len(stack) == 0:
				stack.append(s[i])
				moves += 1
			elif stack[-1] == '(':
				stack.pop()
			else:
				stack.append(s[i])
				moves += 1
		elif s[i] == '(':
			stack.append(s[i])
	return moves
t = int(input())
while t > 0:
	l = int(input())
	s = input()
	moves = check(s)
	print(moves)
	t -= 1


t = int(input())
while t:
	n = int(input())
	s = input()
	count = 0
	moves = 0
	set1 = set()
	for i in s:
		if i == ')':
			count -= 1
			if count < 0:
				if count not in set1:
					moves += 1
					set1.add(count)
		else:
			count += 1
	print(moves)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	br = input()
	count = 0
	mis_cnt = 0
	for i in range(n):
		if br[i] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			count = 0
			mis_cnt += 1
	print(mis_cnt)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		n = II()
		s = SI()
		ans = 0
		cnt = 0
		for c in s:
			if c == '(':
				cnt -= 1
			else:
				cnt += 1
			ans = max(ans, cnt)
		print(ans)
main()


import string
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	openn = 0
	close = 0
	wrong = 0
	for i in s:
		if i == '(':
			openn += 1
		elif i == ')':
			close += 1
		if close > openn:
			wrong += close - openn
			openn = 0
			close = 0
		if close == openn:
			openn = 0
			close = 0
	print(wrong)


for i in ' ' * int(input()):
	n = int(input())
	a = input()
	while a.find('()') >= 0:
		a = a.replace('()', '')
	print(len(a) // 2)


t = int(input())
for i in range(t):
	d = int(input())
	a = list(input())
	s = []
	for j in a:
		if j == '(':
			s.append('(')
		elif s:
			s.pop()
		else:
			pass
	print(len(s))


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
from collections import defaultdict as vector
from collections import deque as que
inin = lambda : int(input())
inar = lambda : list(map(int, input().split()))
from math import log
Testcase = inin()
for _ in range(Testcase):
	st = []
	n = inin()
	s = input()
	s = list(s)
	for i in s:
		if i == '(':
			st.append('(')
		if i == ')':
			if st == []:
				st.append(i)
			elif st[-1] == '(':
				st.pop()
			else:
				st.append(i)
	print(len(st) // 2)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	ob = 0
	count = 0
	for i in range(n - 1):
		if s[i] == ')':
			ob -= 1
		elif s[i] == '(':
			ob += 1
		if ob <= -1:
			for j in range(n - 1, i, -1):
				if s[j] == '(':
					ob += 1
					count += 1
					break
	print(count)


ll = lambda : list(map(int, input().split()))
st = lambda : input()
v = lambda : map(int, input().split())
ii = lambda : int(input())
from collections import *
from math import *
for _ in range(ii()):
	n = ii()
	s = st()
	d = deque()
	for i in s:
		if not d:
			d.append(i)
		elif d[-1] == '(' and i == ')':
			d.pop()
		else:
			d.append(i)
	if len(d) == 0:
		print(0)
	else:
		print(len(d) // 2)


for _ in range(int(input())):
	ans = 0
	n = int(input())
	a = str(input())
	c = 0
	for i in range(n):
		if a[i] == '(':
			c = c + 1
		else:
			c = c - 1
		if ans > c:
			ans = c
	print(-1 * ans)


t = int(input())
while t > 0:
	count_1 = 0
	str_len = int(input())
	string = input()
	for i in range(str_len):
		if string[i] == '(':
			count_1 += 1
		elif count_1 > 0:
			count_1 -= 1
	print(count_1)
	t -= 1


a = int(input())
for i in range(a):
	x = int(input())
	li = input()
	(count1, count2) = (0, 0)
	ans = 0
	for i in li:
		if i == '(':
			count1 += 1
		elif i == ')':
			count2 += 1
			b = count1 - count2
			if b < 0:
				ans += 1
				count2 -= 1
	print(ans)


for i in range(int(input())):
	num_b = int(input())
	b_str = input()
	count = 0
	moves = 0
	min_count = 0
	for item in b_str:
		if item == '(':
			count += 1
		elif item == ')':
			count -= 1
			if count < min_count:
				moves += 1
				min_count = count
	print(moves)


def check(s):
	n = len(s)
	if n == 0:
		return False
	for i in range(1, n):
		if s[i] == ')' and s[i - 1] == '(':
			return True
	return False
t = int(input())
for _ in range(t):
	n = int(input())
	s = [i for i in input()]
	ns = s.copy()
	while check(s):
		s = ns.copy()
		r = 0
		for i in range(1, len(s)):
			if s[i] == ')' and s[i - 1] == '(':
				ns.pop(i)
				ns.pop(i - 1)
				break
	print(len(ns) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ob = 0
	cb = 0
	count = 0
	for i in s:
		if i == '(':
			ob += 1
		elif i == ')':
			cb += 1
		if cb > ob:
			count += 1
			cb = 0
			ob = 0
	print(count)


import sys, os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
sys.setrecursionlimit(10 ** 5)

def mod():
	return 1000000007

def si():
	return sys.stdin.readline().strip()

def ii():
	return int(sys.stdin.readline())

def li():
	return list(sys.stdin.readline().strip())

def mii():
	return map(int, sys.stdin.readline().split())

def lii():
	return list(map(int, sys.stdin.readline().strip().split()))

def solve():
	a = ii()
	b = si()
	c = ans = 0
	for i in range(a):
		if b[i] == '(':
			c += 1
		else:
			c -= 1
			if c < 0:
				c = 0
				ans += 1
	print(ans)
for _ in range(ii()):
	solve()


from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
import math
rl = lambda : stdin.readline()
rll = lambda : stdin.readline().split()
rli = lambda : map(int, stdin.readline().split())
rlf = lambda : map(float, stdin.readline().split())
(INF, NINF) = (float('inf'), float('-inf'))

def main():

	def locmin(L, i):
		(left, right) = (INF, INF)
		if i > 0:
			left = L[i - 1]
		if i < len(L) - 1:
			right = L[i + 1]
		return left > L[i] and L[i] < right
	sgn = lambda x: -1 if x < 0 else 1

	def grp(L):
		ans = []
		(sign, currlen, currmin) = (None, 0, INF)
		for (i, a) in enumerate(L):
			if sgn(a) != sign:
				if sign is not None:
					ans.append((sign, currlen, currmin))
				(sign, currlen, currmin) = (sgn(a), 1, a)
			else:
				currlen += 1
				currmin = min(currmin, a)
		if currlen > 0:
			ans.append((sign, currlen, currmin))
		return ans
	T = int(rl())
	for _ in range(T):
		n = int(rl())
		S = list(rll()[0])
		(currB, B) = (0, [])
		for paren in S:
			if paren == '(':
				currB += 1
			else:
				currB -= 1
			B.append(currB)
		ans = 0
		min_so_far = 0
		for (i, b) in enumerate(B):
			if locmin(B, i) and b < min_so_far:
				ans += abs(b - min_so_far)
				min_so_far = b
		print(ans)
	stdout.close()
main()


def gen_bracket_sequence(n):
	return '()' if n == 1 else '(' + gen_bracket_sequence(n - 1) + ')'

def replace_regular(s):
	old_s = None
	while old_s != s:
		old_s = s
		s = s.replace('()', '')
	return s

def min_moves(s):
	return replace_regular(s).count(')')
t = int(input())
for i in range(0, t):
	n = int(input())
	s = input()
	print(min_moves(s))


for i in range(int(input())):
	n = int(input())
	v = list(str(input()))
	(first, second, ans) = (0, 0, 0)
	for el in v:
		if el == '(':
			first += 1
		else:
			second += 1
		if second > first:
			ans += 1
			(first, second) = (0, 0)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	st = str(input())
	slist = list(st)
	mx = -1
	ans = []
	right = 0
	for j in range(len(slist)):
		if slist[j] == ')':
			if right > 0:
				right -= 1
			else:
				ans.insert(0, slist[j])
				mx = max(mx, len(ans))
		elif len(ans) > 0:
			ans.pop(0)
		else:
			right += 1
	print(max(mx, 0))


t = int(input())
for z in range(t):
	n = int(input())
	s = input()
	while s.find('()') >= 0:
		if s == '()':
			s = ''
			break
		pos = s.find('()')
		s = s[:pos] + s[pos + 2:]
	print(int(len(s) / 2))


for _ in range(int(input())):
	n = int(input())
	lst = list(input())
	(x, y, s) = ('(', ')', [])
	(c1, c2, counter) = (0, 0, 0)
	for i in range(n):
		if lst[i] == x:
			c1 += 1
		else:
			c2 += 1
			if c2 > c1:
				counter = c2 - c1
			s.append(counter)
	print(max(s))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	sub = '()'
	while True:
		if s.find(sub) == -1:
			break
		s = s.replace(sub, '')
	print(len(s) // 2)


n = int(input())
for i in range(n):
	k = int(input())
	s = input()
	ct = 0
	op = 0
	for i in s:
		if i == ')' and op == 0:
			ct += 1
		elif i == ')' and op > 0:
			op -= 1
		else:
			op += 1
	print(ct)


for _ in range(int(input())):
	n = int(input())
	S = input()
	x = 0
	m = 0
	for _ in range(n):
		if S[_] == ')':
			x -= 1
		else:
			x += 1
		if x < m:
			x = m
	print(x)


t = int(input())
for test in range(0, t):
	n = int(input())
	s = input()
	op = clo = ans = 0
	for i in range(0, n):
		if s[i] == '(':
			op += 1
		elif s[i] == ')':
			clo += 1
		if clo > op:
			clo -= 1
			ans += 1
	print(ans)


def main():
	for t in range(int(input())):
		n = int(input())
		s = input()
		ob = 0
		cb = 0
		ans = 0
		for i in s:
			if i == '(':
				ob += 1
			else:
				cb += 1
			if cb > ob:
				ans += 1
				cb -= 1
		print(ans)
main()


def solve():
	n = int(input())
	s = input()
	arr = []
	for c in s:
		if c == '(':
			arr.append(c)
		elif c == ')' and arr:
			arr.pop(-1)
	print(len(arr))
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cursum = [0] * n
	for i in range(n):
		if i == 0:
			if s[i] == '(':
				cursum[i] -= 1
			else:
				cursum[i] += 1
		elif s[i] == '(':
			cursum[i] = cursum[i - 1] - 1
		else:
			cursum[i] = cursum[i - 1] + 1
	print(max(cursum))


def check(s):
	stack = []
	ans = 0
	for i in s:
		if i == '(':
			stack.append(i)
		elif stack:
			stack.pop()
		else:
			ans += 1
	return ans
t = int(input())
while t:
	n = int(input())
	s = input()
	print(check(s))
	t -= 1


for _ in range(int(input())):
	n = int(input())
	ans = 0
	h = 0
	for x in input():
		if '(' == x:
			h -= 1
		else:
			h += 1
		ans = max(ans, h)
	print(ans)


t = int(input(''))
for i in range(t):
	n = int(input(''))
	st = str(input(''))
	count = 0
	moves = 0
	for item in st:
		if item == '(':
			count += 1
		elif count > 0:
			count -= 1
		else:
			moves += 1
	print(moves)


t = input()
for test in range(int(t)):
	len = input()
	brackets = input()
	max_difference = 0
	left_brackets = 0
	right_brackets = 0
	for b in brackets:
		if b == '(':
			left_brackets = left_brackets + 1
		else:
			right_brackets = right_brackets + 1
		diff = right_brackets - left_brackets
		if diff > max_difference:
			max_difference = diff
	print(max_difference)


def get_seq(n, s):
	L = []
	for i in range(n):
		if s[i] == '(':
			L.append(1)
		else:
			L.append(-1)
	i = 0
	a = 0
	b = 0
	count = 0
	while i < n:
		if L[i] == 1:
			a += 1
		elif L[i] == -1:
			b += 1
		if b > a:
			L.pop(i)
			L.append(-1)
			b = b - 1
			count += 1
		else:
			i = i + 1
	return count
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(get_seq(n, s))


import math
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	imbs1 = []
	imbs2 = []
	for i in range(len(s)):
		if s[i] == '(':
			st.append('(')
			imbs2.append(i)
		if s[i] == ')':
			if len(st) > 0:
				if st[0] == '(':
					st.pop(0)
					imbs2.pop(0)
				else:
					imbs1.append(i)
			else:
				imbs1.append(i)
	print(len(imbs1))


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	d = []
	for i in s:
		if i == '(':
			d.append('(')
		elif len(d) > 0 and d[-1] == '(':
			d.pop()
		else:
			d.append(')')
	print(len(d) // 2)


import sys
from collections import defaultdict
name = sys.stdin.read()
jobGrid = []
isJob = True
row = []
grid = name.split('\n')
grid = grid[:-1]
number_of_cases = int(grid[0])
for i in range(number_of_cases):
	l = list(map(str, grid[i * 2 + 2].split()))[0]
	open = 0
	close = 0
	ans = 0
	for j in l:
		if j == ')':
			if close >= open:
				ans += 1
			else:
				close += 1
		else:
			open += 1
	print(ans)


import math
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	f = 0
	ans = 0
	for x in s:
		if x == ')':
			f -= 1
		else:
			f += 1
		if ans > f:
			ans = f
	print(ans * -1)


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	d = 0
	s = []
	for i in range(n):
		s.append(a[i])
	k = 0
	f = 0
	for i in range(n):
		if s[i] == ')' and f == 0:
			k += 1
		elif s[i] == '(':
			f += 1
		else:
			f -= 1
	k += f
	print(k // 2)


num = int(input(''))
for i in range(num):
	amt = int(input(''))
	brackets = input('')
	loop = True
	while loop:
		if brackets.count('()') > 0:
			brackets = brackets.replace('()', '')
		else:
			new = brackets
			loop = False
	print(len(new) // 2)


t = int(input())
for tc in range(t):
	n = int(input())
	line = input()
	arr = []
	for l in range(n):
		arr.append(line[l])
	stack = [arr[0]]
	for sym in range(1, n):
		if len(stack) == 0:
			stack.append(arr[sym])
		elif stack[-1] == '(' and arr[sym] == ')':
			stack.pop()
		else:
			stack.append(arr[sym])
	if len(stack) == 2:
		print('1')
		continue
	print(len(stack) // 2)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	brackets = 0
	ans = 0
	for elem in s:
		if elem == '(':
			brackets += 1
		else:
			brackets -= 1
		if brackets == -1:
			ans += 1
			brackets = 0
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	l = list(s)
	c = 0
	ans = 0
	for j in range(n):
		if l[j] == '(':
			c += 1
		elif l[j] == ')':
			c -= 1
		if c < 0:
			ans += abs(c)
			c = 0
	print(ans)


t = int(input())
kk = 0
while t:
	t -= 1
	n = int(input())
	s = input()
	a = 0
	for i in range(n):
		if s[i] == '(':
			a += 1
		if s[i] == ')':
			if a > 0:
				a -= 1
	print(a)


t = int(input())
for i in range(t):
	l = int(input())
	st = input()
	ocount = 0
	ccount = 0
	toset = 0
	for j in st:
		if j == '(':
			ocount += 1
			if ccount > 0:
				ccount -= 1
		elif j == ')':
			ccount += 1
			if ocount == 0:
				toset += 1
			else:
				ocount -= 1
	print(toset)


a = int(input())
f = []
for i in range(a):
	d = int(input())
	n = input()
	for j in range(d):
		if '()' in n:
			n = n.replace('()', '')
		elif len(set(n)) == 1:
			f.append(len(n))
			break
		else:
			f.append(len(n) // 2)
			break
for i in f:
	print(i)


for _ in range(int(input())):
	n = int(input())
	s = input()
	listt = []
	l = 0
	for x in s:
		if x == '(':
			listt.append('(')
			l += 1
		elif x == ')':
			if l > 0 and listt[l - 1] == '(':
				listt.pop()
				l -= 1
			else:
				listt.append(')')
				l += 1
	print(l // 2)


def swap(i):
	temp = s[i]
	s.pop(i)
	s.append(temp)
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	c1 = 0
	c2 = 0
	i = 0
	count = 0
	while i < n:
		if s[i] == '(':
			c1 += 1
		elif c1 > 0:
			c1 -= 1
		else:
			c1 = 0
			swap(i)
			i -= 1
			count += 1
		i += 1
	print(count)


import sys

class CMoveBrackets:

	def solve(self, tc=0):
		for _ in range(int(input())):
			n = int(input())
			s = input().strip()
			op = 0
			cl = 0
			d = 0
			ans = 0
			for i in range(n):
				if s[i] == '(':
					d += 1
				elif d == 0:
					ans += 1
				else:
					d -= 1
			print(ans)
solver = CMoveBrackets()
input = sys.stdin.readline
solver.solve()


t = int(input())
for testcase in range(t):
	n = int(input())
	s = input()
	n_open = 0
	n_close = 0
	moves = 0
	for bracket in s:
		if bracket == '(':
			n_open += 1
		elif n_open == 0:
			moves += 1
		else:
			n_open -= 1
	print(moves)


def func(s, n):
	stack = []
	for i in range(n):
		if stack == []:
			stack.append(s[i])
		elif s[i] == '(':
			stack.append(s[i])
		elif stack[-1] == '(':
			stack.pop()
		else:
			stack.append(s[i])
	print(len(stack) // 2)
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	func(s, n)


for _ in range(int(input())):
	(N, Moves, Sum) = (int(input()), 0, 0)
	for i in input():
		if i == ')' and Sum <= 0:
			Moves += 1
		elif i == '(':
			Sum += 1
		else:
			Sum -= 1
	print(Moves)


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	count = 0
	r = 0
	i = 0
	while i < n:
		if s[i] == ')':
			if r == 0:
				s = s[:i] + s[i + 1:] + ')'
				i = i - 1
				count = count + 1
			else:
				r = r - 1
		else:
			r = r + 1
		i = i + 1
	print(count)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	s = list(s)
	op = []
	for i in s:
		if i == '(':
			op.append(i)
		if i == ')' and len(op) != 0:
			op.pop()
	print(len(op))


t = int(input())
for z in range(t):
	n = int(input())
	s = input()
	i = 0
	move = 0
	a = []
	while i < n:
		if s[i] == '(':
			a.append(s[i])
		elif len(a) == 0:
			move += 1
		else:
			a.pop()
		i += 1
	print(move)


t = int(input())
for q in range(t):
	lbrak = 0
	c = 0
	n = int(input())
	l = list(input())
	for i in range(n):
		if l[i] == ')':
			if lbrak > 0:
				lbrak -= 1
			else:
				c += 1
		else:
			lbrak += 1
	print(c)


import sys
import math
input = lambda : sys.stdin.readline().rstrip()

def solve(s):
	result = 0
	temp = 0
	for ss in s:
		if ss == '(':
			temp += 1
		if ss == ')':
			temp -= 1
			if temp < 0:
				temp = 0
				result += 1
	return result

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		print(solve(s))
main()


T = int(input())
for tc in range(1, T + 1):
	n = int(input())
	s = str(input())
	ans = 0
	cnt = 0
	for i in s:
		if i == ')':
			cnt += 1
		else:
			cnt -= 1
		if ans < cnt:
			ans = cnt
	print(ans)


t = int(input())
for i in range(t):
	N = int(input())
	s = input()
	op = 0
	close = 0
	ans = 0
	for i in range(N):
		ch = s[i]
		if ch == '(':
			op += 1
			close -= 1
		else:
			close += 1
			if close > ans:
				ans = close
			op -= 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	f = list(str(input()))
	s_open = 0
	answer_open = 0
	s_close = 0
	answer_close = 0
	for i in range(len(f)):
		if f[i] == ')':
			if s_open > 0:
				s_open -= 1
			else:
				answer_open += 1
		else:
			s_open += 1
	print(answer_open)


t = int(input())
while t:
	n = input()
	s = input()
	(lopen, ropen) = (0, 0)
	for i in s:
		if i == '(':
			lopen += 1
		elif lopen != 0:
			lopen -= 1
	print(abs(lopen))
	t -= 1


t = int(input())
i = 0
while i < t:
	n = int(input())
	s = input()
	j = 0
	start = 0
	end = 0
	big = 0
	while j < n:
		if s[j] == '(':
			start += 1
		elif s[j] == ')':
			end += 1
		if end > start:
			big += 1
			start = 0
			end = 0
		j += 1
	print(big)
	i += 1


for _ in range(int(input())):
	n = int(input())
	arr = list(input().strip())
	stack = [arr[0]]
	arr.pop(0)
	for a in arr:
		if stack and stack[-1] == '(' and (a == ')'):
			stack.pop()
		else:
			stack.append(a)
	print(len(stack) // 2)


for _ in range(int(input())):
	t = int(input())
	v = input()
	(start, end) = (0, 0)
	for i in v:
		if i == '(':
			start += 1
		elif start > 0:
			start -= 1
		else:
			end += 1
	print(end)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	a = int(input())
	s = list(input().rstrip())
	maxx = 0
	counter = 0
	for char in s:
		if char == '(':
			counter -= 1
		if char == ')':
			counter += 1
		maxx = max(counter, maxx)
	print(maxx)


from collections import deque
t = int(input())
while t > 0:
	n = int(input())
	t -= 1
	stack = deque()
	count = 0
	s = input()
	for x in s:
		if x == '(':
			stack.append(x)
		elif x == ')' and stack:
			if stack[-1] == '(':
				stack.pop()
			else:
				count += 1
		else:
			count += 1
	print(count)


TC = int(input())

def solution(s):
	z = []
	for i in s:
		if i == '(':
			z.append('(')
		elif len(z) == 0 or z[-1] == ')':
			z.append(')')
		else:
			z.pop()
	return len(z) // 2
for _ in range(TC):
	l = int(input())
	s = input()
	print(solution(s))


for _ in range(int(input())):
	n = int(input())
	s = input()
	n = 0
	while len(s) != 0:
		if s[0] == '(':
			s = s[1:]
			s = s.replace(')', '', 1)
		else:
			n += 1
			s = s[1:]
			s.replace('(', '', 1)
	print(n)


def string_connect(s, ind):
	lis = list(s)
	del lis[ind]
	s = ''.join(lis)
	return s
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	stack = []
	top = 0
	wrong_cnt = 0
	for i in range(n):
		if len(stack) == 0 and s[i] == ')':
			wrong_cnt += 1
		if s[i] == '(':
			stack.append(s[i])
			top += 1
		elif len(stack) > 0 and s[i] == ')':
			top -= 1
			del stack[top]
	print(len(stack))


for test_case in range(int(input())):
	num = int(input())
	brackets = list(input())
	moves = 0
	right = 0
	left = 0
	for bracket in brackets:
		if bracket == ')':
			left += 1
			if left > right:
				left -= 1
				moves += 1
		else:
			right += 1
	print(moves)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	crct = wrng = 0
	for ch in s:
		if ch == ')':
			wrng += 1
			if crct:
				crct -= 1
				wrng -= 1
		else:
			crct += 1
	print(wrng)


t = int(input())
for _ in range(t):
	n = int(input())
	p = input()
	closedStack = []
	openStack = []
	for d in p:
		if d == '(':
			openStack.append(d)
		if d == ')':
			if len(openStack) > 0:
				openStack.pop(-1)
			else:
				closedStack.append(d)
	print(len(closedStack))


(t, *f) = open(0).read().split()
s = f[1::2]
for x in s:
	o = 0
	c = 0
	ans = 0
	for b in x:
		if b == '(':
			o += 1
		else:
			c += 1
			if c > o:
				ans += 1
				c -= 1
	print(ans)


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for j in s:
		if j == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			ans = max(abs(c), ans)
	print(ans)


t = int(input())
for test in range(t):
	n = int(input())
	s = input()
	balance = 0
	result = 0
	for i in range(len(s)):
		if s[i] == '(':
			balance += 1
		else:
			balance -= 1
		if balance < 0:
			result += 1
			balance = 0
	print(result)


import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7
for _ in range(iinput()):
	n = iinput()
	expr = input()
	s = []
	for i in range(n):
		if expr[i] == ')' and len(s):
			if s[0] == '(':
				s.pop(0)
			else:
				s.insert(0, expr[i])
		else:
			s.insert(0, expr[i])
	print(len(s) // 2)


tc = int(input())
for _ in range(tc):
	n = int(input())
	brackets = list(input())
	count = 0
	for b in brackets:
		if b == '(':
			count += 1
		else:
			count = max(0, count - 1)
	print(count)


import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = []
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors.append(i)
			n //= i
		i += 1
	if n > 1:
		factors.append(n)
	return factors

def vars():
	return map(int, input().split())

def array():
	return list(map(int, input().split()))

def main():
	n = int(input())
	stack = []
	s = input()
	for i in range(n):
		if s[i] == '(':
			stack.append('(')
		elif stack and s[i] == ')':
			stack.pop(-1)
	if stack:
		nc = len(stack)
		print(nc)
	else:
		print(0)
t = int(input())
for _ in range(t):
	main()


t = int(input())
for i in range(t):
	n = int(input())
	line = input()
	stack = []
	for (i, c) in enumerate(line):
		if len(stack) > 0 and stack[-1] == '(' and (c == ')'):
			stack.pop()
		else:
			stack.append(c)
	print(int(len(stack) / 2))


def main():
	t = int(input())
	for i in range(t):
		solve()

def solve():
	n = int(input())
	arr = list(input())
	index = 0
	left = 0
	right = 0
	while index < len(arr):
		if arr[index] == '(':
			left += 1
		elif left > 0:
			left -= 1
		else:
			right += 1
		index += 1
	print(left)
main()


import math
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	op = 0
	cl = 0
	for item in s:
		if item == '(':
			op += 1
		elif op == 0:
			cl += 1
		else:
			op -= 1
	print(op)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ma = -1
	mi = 1
	t = 0
	for c in s:
		if c == '(':
			t += 1
			ma = max(ma, t)
		else:
			t -= 1
			mi = min(mi, t)
	print(abs(mi))


t = int(input())
for i in range(t):
	input()
	c = 0
	w = 0
	s = input()
	for ch in s:
		if ch == '(':
			c += 1
		elif c > 0:
			c -= 1
		else:
			w += 1
	print(w)


t = int(input())
while t > 0:
	l = int(input())
	s = input()
	bal = 0
	times = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				times += 1
	print(times)
	t -= 1


t = int(input())
for x in range(t):
	n = int(input())
	s = list(input())
	l1 = []
	l2 = []
	for i in s:
		if i == '(':
			l1.append(i)
		elif len(l1) != 0:
			l1.pop(0)
		else:
			l2.append(i)
	print(len(l2))


test = int(input())
while test != 0:
	n = int(input())
	s = input()
	stack = []
	i = 0
	count = 0
	while i < n:
		if s[i] == '(':
			stack.append('(')
		elif len(stack) != 0:
			stack.pop()
		else:
			count += 1
		i += 1
	print(count)
	test -= 1


for _ in range(int(input())):
	N = int(input())
	stack = []
	s = input()
	for i in range(N):
		if s[i] == '(':
			stack.append(s[i])
		elif len(stack) > 0:
			if stack[-1] == '(':
				stack.pop()
			else:
				stack.append(s[i])
		else:
			stack.append(s[i])
	print(len(stack) // 2)


z = int(input())
for h in range(z):
	n = int(input())
	s = input()
	x = 0
	y = 0
	cnt = 0
	for i in range(n):
		if s[i] == '(':
			x += 1
		elif x > 0:
			x -= 1
		else:
			cnt += 1
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	depth = 0
	s = list(input())
	maxi = 0
	for i in s:
		if i == ')':
			depth -= 1
		else:
			depth += 1
		if depth < 0:
			maxi = max(maxi, abs(depth))
	print(maxi)


t = int(input())
for test in range(t):
	n = int(input())
	s = input()
	count = 0
	bal = 0
	for i in range(n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				count += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	c = 0
	count = 0
	for i in range(n):
		if s[i] == '(':
			c = c + 1
		if s[i] == ')':
			c = c - 1
		if c < 0:
			count += 1
			c = 0
	print(count)


t = int(input())
while t:
	n = int(input())
	s = input()
	ans = []
	front = 0
	cnt = 0
	for i in range(len(s)):
		ele = s[i]
		if s[i] == '(':
			front += 1
			ans.append(s[i])
		elif front <= 0:
			front = 0
			cnt += 1
		else:
			front -= 1
			ans.append(s[i])
	print(cnt)
	t -= 1


def solve():
	a = int(input())
	st = input()
	stack = []
	top = -1
	for br in st:
		if top > -1 and stack[-1] == '(' and (br == ')'):
			stack.pop()
			top -= 1
		else:
			top += 1
			stack.append(br)
	return len(stack) // 2

def main():
	m = int(input())
	while m:
		print(solve())
		m -= 1
main()


t = int(input())
for j in range(t):
	n = int(input())
	d = n
	s = input()
	k = 0
	while '()' in s:
		for i in range(n - 1):
			if s[i:i + 2] == '()':
				s = s[:i] + s[i + 2:]
				d -= 2
	print(d // 2)


from sys import stdin
a = int(stdin.readline().rstrip())
for i in range(a):
	n = int(input())
	z = stdin.readline()
	s = []
	for i in range(n):
		if s:
			if s[-1] == '(' and z[i] == ')':
				s.pop(-1)
			else:
				s.append(z[i])
		else:
			s.append(z[i])
	print(len(s) // 2)


def minstepsBU(n, br):
	k = 0
	new = []
	curopen = 0
	curclose = 0
	maxoc = n // 2
	for i in range(n):
		if br[i] == ')':
			curclose += 1
		else:
			curopen += 1
		if curclose > curopen:
			k += 1
			curclose -= 1
	return k
for t in range(int(input())):
	n = int(input())
	br = input()
	print(minstepsBU(n, br))


t = int(input())
while t != 0:
	lst = []
	count = 0
	n = int(input())
	s = input()
	for i in range(n):
		if s[i] == '(':
			lst.append(1)
		else:
			lst.append(-1)
	res = 0
	i = 0
	while i < n:
		res += lst[i]
		if res < 0:
			lst.append(lst[i])
			lst.pop(i)
			count += 1
			i -= 1
			res = 0
		i += 1
	print(count)
	t -= 1


for i in range(int(input())):
	n = int(input())
	l = list(input())
	a = '('
	b = ')'
	o = []
	(count1, count2) = (0, 0)
	c = 0
	for i in range(n):
		if l[i] == a:
			count1 += 1
		else:
			count2 += 1
			if count2 > count1:
				c = count2 - count1
			o.append(c)
	print(max(o))


for t in range(int(input())):
	length = int(input())
	list1 = input()
	list1 = list(list1)
	counter = 0
	i = 0
	switch = 0
	while i < len(list1):
		if list1[i] == ')':
			counter -= 1
		elif list1[i] == '(':
			counter += 1
		if counter == 0:
			if i == len(list1) - 1:
				break
			else:
				list1 = list1[i + 1:]
				i = 0
				continue
		if counter < 0:
			ele = list1.pop(i)
			list1.append(ele)
			switch += 1
			i = 0
			counter = 0
			continue
		i += 1
	print(switch)


def checker(n, s):
	(a, res) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			a += 1
		else:
			a -= 1
		if a < 0:
			res += 1
			a = 0
	return res
for _ in range(int(input())):
	m = int(input())
	t = input()
	print(checker(m, t))


t = int(input())
for j in range(t):
	n = int(input())
	s = input()
	for i in range(n):
		s = s.replace('()', '')
	print(int(len(s) / 2))


t = int(input())
for _ in range(t):
	n = input()
	string = input()
	l = 0
	r = 0
	counter = 0
	for i in string:
		if i == ')':
			if l == 0:
				counter += 1
			else:
				l -= 1
		else:
			l += 1
	print(counter)


def f(s):
	start_error = 0
	stack = 0
	for (i, c) in enumerate(s):
		stack += 1 if c == '(' else -1
		if stack < 0:
			start_error += 1
			stack = 0
	return start_error
t = int(input())
for _ in range(t):
	int(input())
	print(f(input()))


t = int(input())
for _ in range(t):
	n = int(input())
	l = input()
	i = 0
	j = 0
	for k in l:
		if k == '(':
			i += 1
		elif i > 0:
			i -= 1
		else:
			j += 1
	print(j)


import sys
infile = sys.stdin
next(infile)
for line in infile:
	n = int(line)
	a = infile.readline()
	s = 0
	a = a[0:-1]
	step = 0
	i = 0
	while i < n - 1:
		if a[i] == '(':
			s += 1
		else:
			s -= 1
		if s < 0:
			a = a.replace(')', '', 1)
			a = a + ')'
			step += 1
			s += 1
		else:
			i = i + 1
	print(step)


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input().rstrip()
	op = 0
	cl = 0
	ans = 0
	for i in s:
		if i == '(':
			op += 1
		else:
			cl += 1
		if cl > op:
			s += ')'
			ans += 1
			cl -= 1
	print(ans)


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input().strip()
	res = 0
	c = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			res += 1
			c = 0
	print(res)


def brackets():
	num = int(input())
	open = 0
	close = 0
	move = 0
	for character in input():
		if character == '(':
			open += 1
		elif character == ')':
			close += 1
			if close > open:
				move += 1
				close -= 1
	print(move)
cases = range(int(input()))
for case in cases:
	brackets()


from sys import stdin, stdout
from itertools import combinations
from collections import defaultdict, Counter
import math

def listIn():
	return list(map(int, stdin.readline().strip().split()))

def stringListIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def stringIn():
	return stdin.readline().strip()
t = intIn()
while t > 0:
	t -= 1
	n = intIn()
	bracket = input()
	li = []
	for i in range(n):
		if bracket[i] == ')':
			if len(li) > 0:
				if li[-1] == '(':
					li.pop(-1)
				else:
					li.append(')')
			else:
				li.append(')')
		else:
			li.append('(')
	print(len(li) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ct = 0
	cnt = 0
	mx = 0
	for i in s:
		if i == '(':
			ct -= 1
		else:
			ct += 1
			if ct > 0 and ct > mx:
				cnt += 1
				mx = cnt
	print(cnt)


from math import log
for _ in range(int(input())):
	n = int(input())
	s = input()
	s1 = 0
	s2 = 0
	for i in s:
		if i == '(':
			s1 += 1
		elif s1 != 0:
			s1 -= 1
		else:
			s2 += 1
	print(abs(s1 + s2) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ss = 0
	c = 0
	for i in range(n):
		if s[i] == '(':
			ss += 1
		elif s[i] == ')':
			ss -= 1
		if ss < 0:
			c += 1
			ss = 0
	print(c)


def getCountOfSorts(listOfBrackets, size):
	bal = 0
	ans = 0
	for x in listOfBrackets:
		if x == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				ans += 1
				bal = 0
	print(ans)
n = int(input())
for i in range(n):
	size = int(input())
	listOfBrackets = list(input())
	getCountOfSorts(listOfBrackets, size)


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
t = 1
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = input()
	l = 0
	r = 0
	ans = 0
	for i in s:
		if i == '(':
			l += 1
		else:
			r += 1
		if l >= r:
			continue
		else:
			ans += 1
			l += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	balance = 0
	counter = 0
	for i in s:
		if i == '(':
			balance += 1
		else:
			balance -= 1
			if balance < 0:
				counter += 1
				balance = 0
	print(counter)


for ii in range(int(input())):
	n = int(input())
	s = input()
	a = list(s)
	l = [s[0]]
	for i in range(1, n):
		if len(l) == 0:
			l.append(s[i])
		elif s[i] == ')' and l[-1] == '(':
			l.pop()
		else:
			l.append(s[i])
	ans = len(l) // 2
	print(ans)


tl = input()
for t in range(int(tl)):
	n = int(input())
	s = input()
	st = []
	for c in s:
		if st:
			if c == ')' and st[-1] == '(':
				st.pop()
			else:
				st.append(c)
				if len(st) > 1 and st[-2] == '(' and (st[-1] == ')'):
					(st.pop(), st.pop())
		else:
			st.append(c)
	print(len(st) // 2)


test = int(input())
for _ in range(test):
	n = int(input())
	st = input()
	stack = []
	count = 0
	for i in range(n):
		if st[i] == ')':
			if len(stack) == 0:
				count += 1
			else:
				stack.pop()
		else:
			stack.append(st[i])
	print(count)


def brackets(n, st):
	summ = 0
	cnt = 0
	for s in st:
		if s == '(':
			summ += 1
		elif s == ')' and summ > 0:
			summ -= 1
		elif s == ')' and summ == 0:
			cnt += 1
	print(cnt)
for _ in range(int(input())):
	n = int(input())
	s = input()
	brackets(n, s)


ans = ''
for _ in range(int(input())):
	n = int(input())
	s = input()
	o = 0
	c = 0
	for i in s:
		if i == ')':
			if o > 0:
				o -= 1
			else:
				c += 1
		else:
			o += 1
	cnt = 0
	if o != 0 and c != 0:
		cnt = o
	ans += str(cnt) + '\n'
print(ans)


def ab(expr):
	stack = []
	k = 0
	for char in expr:
		if char == '(':
			stack.append(char)
		else:
			if not stack:
				k = k + 1
			if len(stack) > 0:
				current_char = stack.pop()
				if current_char == '(':
					if char != ')':
						k = k + 1
	print(k)
n = int(input())
for i in range(n):
	m = int(input())
	n = input()
	ab(n)


t = int(input())

def num_move(brackets):
	stack = []
	for bracket in brackets:
		if bracket == '(':
			stack.append(bracket)
		elif stack and stack[-1] == '(':
			stack.pop()
		else:
			stack.append(bracket)
	return len(stack) // 2
for i in range(t):
	num = int(input())
	brackets = input()
	print(num_move(brackets))


import sys
input = sys.stdin.readline
t = int(input())
for t1 in range(t):
	n = int(input())
	s = input()
	s = s.strip()
	l = []
	l.append(s[0])
	for i in range(1, n):
		if s[i] == ')' and len(l) > 0 and (l[-1] == '('):
			l.pop()
		else:
			l.append(s[i])
	print(len(l) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	bracketSeq = input()
	ctr = 0
	for i in bracketSeq:
		if ctr == 0 and i == ')':
			continue
		elif i == '(':
			ctr += 1
		else:
			ctr -= 1
	print(ctr)


n = int(input())
for i in range(n):
	l = []
	t = int(input())
	r = list(input())
	res = 0
	for j in r:
		if j == '(':
			l.append(j)
		elif l == [] and j == '(':
			l.append(j)
		elif l == [] and j == ')':
			res += 1
		else:
			l.pop()
	print(res)


cases = []
for i in range(int(input())):
	input()
	cases.append(list(input()))

def solve(case):
	d = 0
	moves = 0
	for l in case:
		if l == '(':
			d += 1
		else:
			d -= 1
			if d < 0:
				moves = min(d, moves)
	print(-moves)
for case in cases:
	solve(case)


for _ in range(int(input())):
	n = int(input())
	bra = input()
	stack = []
	moves = 0
	for i in range(n):
		if bra[i] == '(':
			stack.append(bra[i])
		if bra[i] == ')':
			if len(stack) > 0 and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(bra[i])
	print(len(stack) // 2)


test_cases = int(input())
for t in range(test_cases):
	n = int(input())
	s = input()
	count = 0
	max_depth = 0
	for b in s:
		if b == ')':
			count += 1
		if b == '(':
			count -= 1
		max_depth = max(count, max_depth)
	print(max_depth)


def solution(s):
	n = 0
	(openers, closers) = (0, 0)
	for b in s:
		if b == '(':
			openers += 1
		if b == ')':
			closers += 1
			if closers > openers:
				n += 1
				(openers, closers) = (0, 0)
	return n
n = int(input())
for _ in range(n):
	n = int(input())
	s = input()
	print(solution(s))


t = int(input())
i = 0
while i < t:
	n = int(input())
	s = input()
	stack = []
	count = 0
	for x in range(n):
		if s[x] == '(':
			stack.append(s[x])
		elif len(stack) == 0:
			stack.append(s[x])
		elif stack[-1] == '(':
			stack.pop()
		else:
			stack.append(s[x])
	while len(stack) != 0 and stack[-1] == '(':
		stack.pop()
	print(len(stack))
	i = i + 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	(x, y) = (0, 0)
	for c in s:
		if st == []:
			if c == '(':
				st.append('(')
			else:
				y += 1
		elif c == '(':
			st.append(c)
		else:
			st.pop()
	print(y)


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	(i, c) = (0, 0)
	r = []
	while i < n:
		if a[i] == '(':
			r.append('(')
			i += 1
		elif '(' in r:
			r.remove('(')
			i += 1
		else:
			b = a.pop(i)
			c += 1
			a.append(b)
	print(c)


from sys import stdin
t = int(stdin.readline().strip())
for i in range(t):
	n = int(stdin.readline().strip())
	s = stdin.readline().strip()
	x = 0
	ans = 0
	for c in s:
		if c == '(':
			x += 1
		else:
			x -= 1
		ans = min(ans, x)
	print(-1 * ans)


for _ in range(int(input())):
	r = int(input())
	t = input()
	c = 1
	while c > 0:
		c = t.count('()')
		t = t.replace('()', '')
	print(t.count('('))


for j in range(int(input())):
	n = int(input())
	s = input()
	am1 = 0
	am2 = 0
	am = 0
	ma = 0
	am3 = 0
	am4 = 0
	for i in range(n):
		if s[i] == '(':
			am1 += 1
		else:
			am2 += 1
		if am1 - am2 == -1:
			am += 1
			am2 -= 1
		if s[n - i - 1] == '(':
			am3 += 1
		else:
			am4 += 1
		if am3 - am4 == 1:
			am3 -= 1
			ma += 1
		if am4 == n // 2 and am1 == n // 2:
			print(min(am, ma))
			break


def solve(n, s):
	rj = 0
	mi = 9999999999999
	ma = -9999999999999999
	for c in s:
		if c == '(':
			rj += 1
		else:
			rj -= 1
		if rj < mi:
			mi = rj
		if rj > ma:
			ma = rj
	return -mi
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(solve(n, s))


import math
T = int(input())
for t in range(T):
	n = int(input())
	scopes = []
	for x in input():
		if x == '(':
			scopes.append(x)
		elif len(scopes) > 0:
			scopes.pop()
	print(len(scopes))


T = int(input())
for i in range(T):
	n = int(input())
	Brackets = input()
	Brack = [Brackets[k] for k in range(n)]
	moves = 0
	j = 0
	Stack = []
	while j < n:
		if Brack[j] == '(':
			Stack.append('(')
			j += 1
		elif len(Stack) == 0:
			moves += 1
			Brack.pop(j)
			Brack.append(')')
		else:
			Stack.pop()
			j += 1
	print(moves)


for _ in ' ' * int(input()):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


def dtb(n):
	return bin(n).replace('0b', '')

def btd(n):
	return int(n, 2)
t = int(input())
for k in range(t):
	n = int(input())
	s = input().strip()
	(ans, c) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			c += 1
		elif s[i] == ')':
			c -= 1
		if c < 0:
			ans += 1
			c = 0
	print(ans)


from collections import deque
t = int(input())
for q in range(0, t):
	n = int(input())
	a = input()
	stack = deque()
	for i in range(0, n):
		if a[i] == '(':
			stack.append(1)
		elif len(stack) != 0:
			stack.pop()
	print(len(stack))


import sys
input = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	s = input().split()[0]
	st = []
	cou = 0
	for i in s:
		if i == '(':
			st.append(i)
		elif st:
			st.pop()
		else:
			cou += 1
	cou += len(st)
	print(cou // 2)
	t -= 1


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for _ in range(int(input())):
	q = int(input())
	w = input()
	k = 0
	l = 0
	r = 0
	for i in w:
		if i == '(':
			k -= 1
		else:
			k += 1
			if k > 0 and k > r:
				r = k
				l += 1
	print(l)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	input()
	ss = input()
	depth = 0
	count = 0
	for s in ss:
		if depth == 0 and s == ')':
			count += 1
		elif s == '(':
			depth += 1
		else:
			depth -= 1
	print(count)

def main():
	t = int(inputi())
	for _ in range(t):
		solve()
main()


import sys
from collections import defaultdict
TEST = 0
if TEST == 1:
	input_file = open('inputC.txt', 'r')
	input_from_file = input_file.readlines()

def read_int():
	if TEST:
		return int(input_from_file.pop(0))
	else:
		return int(sys.stdin.readline())

def read_ints():
	if TEST:
		return list(map(int, input_from_file.pop(0).rstrip().split()))
	else:
		return list(map(int, sys.stdin.readline().split()))

def read_str():
	if TEST:
		in1 = input_from_file.pop(0).rstrip()
	else:
		in1 = sys.stdin.readline().rstrip()
	return in1
t = read_int()
for test in range(t):
	n = read_int()
	s = read_str()
	open = 0
	close = 0
	wrongclose = 0
	for c in s:
		if c is '(':
			open += 1
		else:
			if close >= open + wrongclose:
				wrongclose += 1
			close += 1
	print(wrongclose)


def find(s):
	stack = []
	for x in s:
		if x == ')':
			if stack:
				if stack[-1] == '(':
					stack.pop()
				else:
					stack += [x]
			else:
				stack += [x]
		else:
			stack += [x]
	return len(stack) // 2
for _ in range(int(input())):
	input()
	s = input()
	print(find(s))


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	i = 0
	while i < n:
		x = s[i]
		if len(st) == 0:
			st.append(x)
			i = i + 1
			continue
		if st[-1] == '(' and x == ')':
			st.pop()
			i = i + 1
			continue
		else:
			st.append(x)
			i = i + 1
			continue
	print(len(st) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	countA = 0
	countB = 0
	for x in s:
		if x == '(':
			stack.append(x)
		elif len(stack) == 0:
			countA += 1
		else:
			stack.pop(0)
	print(countA)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = deque()
	sl = 0
	moves = 0
	for ch in s:
		if ch == '(':
			stack.append('(')
			sl += 1
		if ch == ')':
			if sl == 0:
				moves += 1
			else:
				stack.pop()
				sl -= 1
	print(moves)


def solve(s):
	unmatched = 0
	i = 0
	while i < len(s):
		if s[i] == '(':
			unmatched += 1
		elif unmatched > 0:
			while i < len(s) and s[i] != '(' and (unmatched > 0):
				unmatched -= 1
				i += 1
			i -= 1
		i += 1
	print(unmatched)

def main():
	t = int(input())
	for i in range(t):
		input()
		solve(input())
main()


import math

def solve():
	n = int(input())
	s = input()
	bal = 0
	ans = 0
	for i in range(0, n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
			ans = max(ans, -bal)
	print(ans)
t = 1
t = int(input())
for _ in range(0, t):
	solve()


t = int(input())
for _ in range(t):
	n = map(int, input().split())
	s = input()
	d = 0
	m = 0
	for i in s:
		if i == '(':
			d += 1
		elif d == 0:
			m += 1
		else:
			d -= 1
	print(m)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	opening = 0
	close = 0
	moves = 0
	for char in s:
		if char == '(':
			opening += 1
		else:
			close += 1
		if close > opening:
			close -= 1
			moves += 1
	print(moves)


def closeBrackets(length, string):
	counter = 0
	i = 0
	while i < length:
		if string[i] == ')':
			if not counter == 0:
				counter -= 1
		else:
			counter += 1
		i += 1
	return counter
t = int(input())
for _ in range(t):
	length = int(input())
	string = input()
	print(closeBrackets(length, string))


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(int(inp())):
	n = int(inp())
	s = inp()
	ct = 0
	mn = 0
	for i in s:
		if i == '(':
			ct += 1
		else:
			ct -= 1
		mn = min(ct, mn)
	print(abs(mn))


import re
test = int(input())
for t in range(test):
	n = int(input())
	a = input()
	le = len(a)
	while True:
		a = re.sub('\\(\\)', '', a)
		if len(a) == le:
			break
		else:
			le = len(a)
	print(int(len(a) / 2))


num_cases = int(input())
for _ in range(num_cases):
	num_brackets = int(input())
	seq = input()
	open = closed = 0
	for i in seq:
		if i == '(':
			open += 1
		elif i == ')' and open > 0:
			num_brackets -= 2
			open -= 1
	print(num_brackets // 2)


test = int(input())
for _ in range(test):
	n = int(input())
	s = input()
	sco = 0
	ans = 0
	for i in s:
		if i == '(':
			sco += 1
		else:
			sco -= 1
			if sco < 0:
				sco = 0
				ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	left = 0
	res = 0
	for p in s:
		if p == ')':
			if left:
				left -= 1
			else:
				res += 1
		else:
			left += 1
	print(res)


t = input()
t = int(t)
for i in range(t):
	count = 0
	ca = 0
	ans = ''
	val = int(input())
	arr = input()
	n = len(arr)
	for i in range(len(arr)):
		if arr[i] == '(' and count >= 0:
			count += 1
		elif arr[i] == ')' and count > 0:
			count -= 1
		elif arr[i] == '(' and count < 0:
			ans = '(' + ans[:i] + ans[i + 1:]
			i = 0
			ca += 1
			count = 0
		elif arr[i] == ')' and count <= 0:
			ans = ans[:i] + ans[i + 1:] + ')'
			i = 0
			ca += 1
			count = 0
	print(ca)


for tc in range(int(input())):
	n = int(input())
	line = input()
	stack = []
	count = 0
	for i in range(len(line)):
		if len(stack) == 0:
			if line[i] == ')':
				count += 1
			else:
				stack.append(line[i])
		elif line[i] == '(':
			stack.append('(')
		else:
			stack.pop()
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = input()
	count1 = 0
	count2 = 0
	i = 0
	while i != n:
		if s[i] == '(':
			count1 += 1
		else:
			count1 -= 1
		if count1 < 0:
			s = s[:i] + s[i + 1:] + ')'
			i -= 1
			count2 += 1
			count1 += 1
		i += 1
	print(count2)


i = int(input())
for t in range(i):
	f = 0
	k = 0
	inti = int(input())
	s = input()
	for x in s:
		if f > 0 and x == ')':
			k += 1
			f -= 1
		if x == '(':
			f += 1
	print(f)


for _ in range(int(input())):
	n = int(input())
	s = input()
	m = 0
	sm = 0
	for x in s:
		sm += 1 if x == '(' else -1
		m = min(sm, m)
	print(abs(m))


for t in range(int(input())):
	a = int(input())
	n = input()
	ans = a // 2
	st = []
	count = 0
	for i in range(len(n)):
		if n[i] == '(':
			st.append(n[i])
		elif st == []:
			count += 1
		else:
			st.pop(-1)
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	count = 0
	for i in s:
		if i == ')':
			count += 1
	print(count)


for z in range(int(input())):
	length = int(input())
	s = input()
	ans = 0
	stored = 0
	for i in range(length):
		if s[i] == '(':
			stored += 1
		elif s[i] == ')' and stored == 0:
			ans += 1
		elif s[i] == ')' and stored > 0:
			stored -= 1
	print(ans)


def mp():
	return map(int, input().split())

def it():
	return int(input())
for _ in range(it()):
	n = it()
	s = list(input())
	v = []
	ans = 0
	for i in range(n):
		if s[i] == '(':
			v.append(s[i])
		elif v:
			v.pop()
		else:
			ans += 1
	print(ans)


testcase = int(input())
for test in range(testcase):
	lenght = int(input())
	string = input()
	while string.count('()') > 0:
		string = string.replace('()', '')
	res = len(string) // 2
	print(res)


t = int(input())
l = []
for j in range(t):
	t1 = int(input())
	s = input()
	l.append(s)
for k in l:
	for i in range(len(k)):
		if '()' in k:
			k = k.replace('()', '')
	print(len(k) // 2)


for _ in range(int(input())):
	n = int(input())
	l = list(input())
	s = []
	si = 0
	for i in range(n):
		if l[i] == '(':
			s.append(l[i])
			si += 1
		elif si != 0:
			s.pop()
			si -= 1
	print(si)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	count = 0
	temp = 0
	for i in s:
		if i == '(':
			temp += 1
		elif temp <= 0:
			count += 1
		else:
			temp -= 1
	print(count)


t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	m = 0
	c = 0
	for char in s:
		if char == ')':
			c += 1
			m = max(m, c)
		else:
			c -= 1
	print(m)


for _ in range(int(input())):
	lens = int(input())
	seqs = input()
	while '()' in seqs:
		seqs = seqs.replace('()', '')
	print(len(seqs) // 2)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	n = val()
	s = st()
	open = 0
	ans = 0
	for i in s:
		if i == '(':
			open += 1
		elif open > 0:
			open -= 1
		else:
			ans += 1
	print(ans)


t = int(input())
for j in range(t):
	x = int(input())
	s = input()
	ans = []
	for i in s:
		if i == ')':
			ans.append(-1)
		else:
			ans.append(1)
	loc = 0
	i = 0
	r = 0
	while ans and i < len(ans):
		e = ans[i]
		if e == 1:
			loc += 1
		else:
			loc -= 1
		if loc < 0:
			temp = ans.pop(i)
			ans.append(temp)
			r += 1
			loc += 1
		else:
			i += 1
	print(r)


for t in range(int(input())):
	n = int(input())
	s = input()
	dic = {}
	dic[')'] = 0
	dic['('] = 0
	errors = 0
	for i in s:
		if i == ')':
			if dic['('] > 0:
				dic['('] -= 1
			else:
				errors += 1
		elif i == '(':
			dic['('] += 1
	print(errors)


t = int(input())
for _ in range(t):
	n = int(input())
	lis = []
	arr = list(input())
	error = 0
	for i in range(n):
		if len(lis) == 0:
			if arr[i] == '(':
				lis.append('(')
			elif arr[i] == ')':
				error += 1
		elif arr[i] == '(' and lis[-1] == ')':
			error += 1
		elif arr[i] == ')' and lis[-1] == '(':
			lis.pop()
		elif arr[i] == '(' and lis[-1] == '(':
			lis.append('(')
	error += len(lis)
	print(int(error / 2))


n = int(input())
while n != 0:
	ln = int(input())
	brack = input()
	stack = []
	for x in brack:
		if x == '(':
			stack.append('(')
		if x == ')':
			if len(stack) > 0 and stack[len(stack) - 1] == '(':
				stack.pop()
			else:
				stack.append(')')
	if len(stack) > 0:
		if stack.count('(') == stack.count(')'):
			print(stack.count('('))
	if len(stack) == 0:
		print(0)
	n -= 1


def solution(sequence):
	stack = 0
	cnt = 0
	for item in sequence:
		if item == '(':
			stack += 1
		else:
			stack -= 1
			if stack < 0:
				cnt += 1
				stack = 0
	print(cnt)
inp = int(input())
for _ in range(inp):
	input()
	solution(input())


t = int(input())
for _ in range(t):
	n = int(input())
	st = input()
	temp1 = 0
	temp2 = 0
	moves = 0
	for i in range(len(st)):
		ch = st[i]
		if ch == '(':
			temp1 += 1
		if ch == ')':
			temp2 += 1
		if temp2 > temp1:
			moves += 1
			temp2 -= 1
	print(moves)


for i in range(int(input())):
	n = int(input())
	s = list(input())
	x = y = j = ans = int(0)
	while j < len(s):
		if s[j] == '(':
			x += 1
		elif x != 0:
			x -= 1
		else:
			ans += 1
			s.append(')')
		j += 1
	print(ans)


t = int(input())
for i in range(t):
	x = int(input())
	y = input()
	count = 0
	dp = []
	for i in y:
		try:
			if i == ')' and dp[-1] == '(':
				del dp[-1]
			else:
				dp.append(i)
		except IndexError:
			dp.append(i)
	print(int(len(dp) / 2))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	length = int(input())
	s = input().rstrip()
	left = []
	move = 0
	for p in s:
		if p == '(':
			left.append('(')
		elif not left:
			move += 1
		else:
			left.pop()
	print(move)


def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		s = str(input())
		ans = 0
		kol = 0
		mp = 0
		mo = 0
		for j in s:
			if j == ')' and kol >= 0:
				kol += 1
				mp = max(mp, kol)
			elif j == '(' and kol <= 0:
				kol -= 1
				mo = max(mo, kol)
			elif j == ')':
				ans += 1
				kol += 1
			elif j == '(':
				ans += 1
				kol -= 1
		print(mp)
main()


for i in range(int(input())):
	n = int(input())
	s = input()
	b = 0
	k = 0
	for c in s:
		if c == '(':
			b += 1
		else:
			b -= 1
		k = min(k, b)
	print(-k)


for z in range(int(input())):
	n = int(input())
	arr = list(input())
	d = []
	for i in arr:
		if i == '(':
			d.append(i)
		elif len(d) > 0 and d[-1] == '(':
			del d[-1]
		else:
			d.append(i)
	print(len(d) // 2)


import math
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	stack1 = []
	stack2 = []
	count = 0
	for i in s:
		if i == ')':
			if len(stack1) == 0:
				stack2.append(i)
			elif len(stack1) != 0:
				stack1.pop()
		if i == '(':
			stack1.append(i)
	print(len(stack2))


for I in range(int(input())):
	n = int(input())
	s = input()
	left = 0
	right = 0
	res = 0
	for (i, char) in enumerate(s):
		if char == '(':
			left += 1
		if char == ')':
			if left <= right:
				res += 1
			else:
				right += 1
	print(res)


t = int(input())
for i in range(t):
	n = int(input())
	lst = input()
	lst = list(lst)
	stack = []
	for j in range(n):
		if lst[j] == '(':
			stack.append('(')
		elif len(stack) > 0 and lst[j] == ')' and (stack[len(stack) - 1] == '('):
			stack.pop()
		else:
			stack.append(')')
	print(len(stack) // 2)


for _ in range(int(input())):
	n = int(input())
	(s, x, i) = (input(), 0, 0)
	while i < n:
		if s[i] == '(':
			j = i + 1
			check = False
			x += 1
			while j < n:
				if s[j] == '(':
					x += 1
				else:
					break
				j += 1
			while j < n and x:
				if s[j] == ')':
					x -= 1
				else:
					break
				j += 1
			i = j - 1
		i += 1
	print(x)


t = int(input())
i = 0
while i < t:
	l = int(input())
	string = input()
	unbalanced_str = string[0]
	j = 1
	while j < l:
		if unbalanced_str == '':
			unbalanced_str = string[j]
			j += 1
			continue
		if unbalanced_str[-1] == '(' and string[j] == ')':
			unbalanced_str = unbalanced_str[:-1]
		else:
			unbalanced_str = unbalanced_str + string[j]
		j += 1
	print(int(len(unbalanced_str) / 2))
	i += 1


def solve():
	n = int(input().strip())
	s = input().strip()
	opening_count = 0
	closing_count = 0
	problem_count = 0
	for x in s:
		if x == '(':
			opening_count += 1
		elif opening_count <= closing_count:
			problem_count += 1
		else:
			closing_count += 1
	print(problem_count)
t = int(input().strip())
for _ in range(t):
	solve()


for _t in range(int(input())):
	n = int(input())
	s = input()
	st = 0
	c = 0
	for i in s:
		if i == '(':
			st += 1
		elif i == ')' and st > 0:
			st -= 1
		else:
			c += 1
	c += st
	print(c // 2)


def game(s):
	i = 0
	c = 0
	ans = 0
	while i < len(s):
		if s[i] == '(':
			c = c + 1
			i = i + 1
		elif c == 0:
			s = s[:i] + s[i + 1:] + s[i]
			ans += 1
		else:
			c = c - 1
			i = i + 1
	return ans
t = int(input())
while t:
	n = int(input())
	print(game(input()))
	t = t - 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	op = 0
	count = 0
	for j in range(n):
		if s[j] == ')' and op > 0:
			op -= 1
			count += 1
		if s[j] == '(':
			op += 1
			count += 1
	if op == 0:
		print(0)
	else:
		print(n - count)


def solution(k, n):
	countOpen = []
	countClose = []
	for i in range(k):
		if n[i] == '(':
			for j in range(i, k):
				if n[j] == '(':
					countOpen.append(j)
				elif n[j] == ')':
					countClose.append(j)
			break
	if len(countOpen) == 0 or len(countClose) == 0:
		return k / 2
	i = 0
	j = 0
	count = 0
	while True:
		if countOpen[i] < countClose[j]:
			i += 1
			j += 1
			count = count + 1
		else:
			j += 1
		if i == len(countOpen) or j == len(countClose):
			break
	return k / 2 - count
x = int(input())
ans = []
for i in range(x):
	k = int(input())
	n = input()
	ans.append(solution(k, n))
for i in range(len(ans)):
	print(int(ans[i]))


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	p = 0
	for i in s:
		if i == '(':
			p += 1
		elif i == ')':
			p -= 1
		if p < 0:
			p = 0
	print(p)


t = int(input())
for e in range(t):
	n = int(input())
	s = input()
	r = 0
	count = 0
	for i in range(n):
		if s[i] == '(':
			r += 1
		else:
			r -= 1
		if r < 0:
			count += 1
			r = 0
	print(count)


from sys import stdin as lector
input = lector.readlines()
for i in range(2, 2 * int(input[0]) + 1, 2):
	max = 0
	fin = False
	n = ''.join(list(input[i][0:-1].split('()')))
	nn = n
	while fin == False:
		nn = ''.join(list(nn.split('()')))
		if len(n) == len(nn):
			fin = True
		else:
			n = nn
	print(int(len(nn) / 2))


import math
from sys import stdin
from collections import Counter, defaultdict, deque
input = stdin.readline
mod = pow(10, 9) + 7

def solve():
	n = int(input())
	s = input()
	c = 0
	l1 = []
	for i in range(n):
		if s[i] == '(':
			l1.append(1)
		elif len(l1) == 0:
			c = c + 1
		else:
			l1.pop()
	print(c)
for _ in range(int(input())):
	solve()


from sys import stdin
import math
A = int(stdin.readline())
for t in range(0, A):
	B = int(stdin.readline())
	C = stdin.readline()
	count = 0
	ans = 0
	for j in range(0, B):
		if C[j] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			count = 0
			ans += 1
	print(ans)


for k in range(int(input())):
	n = input()
	ar = input()
	ctr = 0
	ans = 0
	for p in ar:
		if p == '(':
			ctr += 1
		else:
			ctr -= 1
		if ctr < 0:
			ans += 1
			ctr = 0
	print(ans)


import math
t = int(input())
for g in range(0, t):
	n = int(input())
	a = []
	s = input()
	for i in range(0, n):
		if s[i] == '(':
			a.append('(')
		elif s[i] == ')' and len(a) >= 1 and (a[len(a) - 1] == '('):
			a.pop()
	print(len(a))


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		dp = 0
		for i in s:
			if i == '(':
				dp += 1
			elif i == ')' and dp > 0:
				dp -= 1
		print(abs(dp))
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	A = []
	for i in s:
		A.append(i)
	i = 0
	j = 1
	count = 0
	c = 0
	while j <= n // 2:
		if A[i] == '(':
			c += 1
			i += 1
			j += 1
		elif A[i] == ')':
			c -= 1
			if c < 0:
				A.remove(')')
				A.append(')')
				c += 1
				count += 1
			else:
				i += 1
	print(count)


for i in range(int(input())):
	a = int(input())
	scopes = input()
	list(scopes)
	count = 0
	ans = 0
	for i in range(len(scopes)):
		if scopes[i] == '(':
			count += 1
		else:
			count -= 1
			if ans >= count:
				ans = count
	print(ans * -1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	op = 0
	cl = 0
	ans = 0
	for i in s:
		if i == '(':
			cl = cl + 1
		else:
			op = op + 1
		if op > cl:
			ans = max(ans, op - cl)
	print(ans)


t = int(input())
for i in range(t):
	total = 0
	l = []
	n = int(input())
	s = input()
	for x in s:
		if x == '(':
			total += 1
		else:
			total -= 1
		l.append(total)
	print(abs(min(l)))


t = int(input())
for kk in range(t):
	num = int(input())
	st = input()
	stack = []
	cnt = 0
	for i in range(num):
		if st[i] == '(':
			stack.append(st[i])
		elif len(stack):
			stack.pop()
		else:
			cnt += 1
	ans = (cnt + len(stack)) // 2
	print(ans)


for i in range(int(input())):
	n = int(input())
	st = input()
	stack = []
	for i in st:
		if i == '(' or i == '{':
			stack.append(i)
		elif stack and i == ')' and (stack[-1] == '('):
			stack.pop(-1)
		elif stack and i == '}' and (stack[-1] == '{'):
			stack.pop(-1)
		else:
			stack.append(i)
	print(len(stack) // 2)


a = int(input())
for i in range(a):
	x = int(input())
	stri = input()
	while '()' in stri:
		m = stri.split('()')
		stri = ''.join(m)
	ans = len(stri) // 2
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = list(input())
	cnt = 0
	stk = []
	i = 0
	while i != len(a):
		if a[i] == '(':
			stk.append(a[i])
		elif len(stk) == 0:
			cnt += 1
			a.append(a[i])
		else:
			stk.pop()
		i += 1
	print(cnt)


for _ in range(int(input())):
	countt = 0
	ans = 0
	n = int(input())
	s = str(input())
	for i in range(0, len(s)):
		if s[i] == '(':
			countt += 1
		else:
			countt -= 1
		if countt == -1:
			ans += 1
			countt += 1
	print(ans)


t = int(input())
for x in range(t):
	n = int(input())
	l1 = input()
	temp = 0
	ans = 0
	for x in range(n):
		if l1[x] == ')':
			temp += 1
		else:
			temp -= 1
		ans = max(temp, ans)
	print(ans)


def f(s):
	while '()' in s:
		s = s.replace('()', '')
	return len(s) // 2
for i in range(int(input())):
	n = int(input())
	s = input()
	print(f(s))


for _ in range(int(input())):
	n = input()
	l = input()
	count = 0
	move = 0
	for i in l:
		if i == '(':
			count += 1
		elif count == 0:
			move += 1
		else:
			count -= 1
	print(move)


def solve():
	n = int(input())
	s = input()
	st = list()
	f = 0
	for i in range(n - 1):
		if s[i] == '(':
			st.append(s[i])
		elif len(st) != 0:
			st.pop()
		else:
			f += 1
	print(f)
for _ in range(int(input())):
	solve()


def func():
	n = int(input())
	s = input()
	count = 0
	res = 0
	for c in s:
		if c == '(':
			count += 1
		elif c == ')':
			if count:
				count -= 1
	print(count)
cases = int(input())
for i in range(cases):
	func()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	l = list(s)
	ans = 0
	r = 0
	for i in range(n):
		if l[i] == '(':
			r += 1
		else:
			r -= 1
			if r < 0:
				r = 0
				ans += 1
	print(ans)


for _ in range(int(input())):
	(N, S) = (int(input()), input())
	A = 0
	P = 0
	for i in range(N):
		if S[i] == ')':
			P -= 1
		else:
			P += 1
		if P < 0:
			P += 1
			A += 1
	print(A)


import sys

def main():
	t = int(next(sys.stdin))
	for _ in range(t):
		next(sys.stdin)
		ln = next(sys.stdin)
		s = ln.strip()
		print(solve(s))

def solve(s):
	ans = bal = 0
	for c in s:
		if c == '(':
			bal += 1
		elif bal > 0:
			bal -= 1
		else:
			ans += 1
	return ans
main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stk = []
	for i in s:
		if len(stk) > 0 and stk[-1] == '(' and (i == ')'):
			stk.pop()
		else:
			stk.append(i)
	c = stk.count(')')
	print(min(c, len(stk) - c))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	m = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if c < 0 and c < m:
			m = c
	print(abs(m))


from collections import deque
T = int(input().strip())
for t in range(T):
	n = int(input().strip())
	a = list(input().strip()[:n])
	opens = 0
	res = 0
	while a:
		cur = a.pop(0)
		if cur == '(':
			opens += 1
		else:
			opens -= 1
		if opens < 0:
			res += 1
			opens += 1
	print(res)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	count = 0
	open = 0
	close = 0
	for x in range(n):
		if s[x] == '(':
			open += 1
		else:
			close += 1
		if close > open:
			count += 1
			close = 0
			open = 0
	print(count)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def integer():
	return int(inp())

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def solve():
	n = integer()
	s = inp()
	co = 0
	ans = 0
	for i in s:
		if i == ')':
			if co <= 0:
				ans += 1
			else:
				co -= 1
		else:
			co += 1
	print(ans)
testcase(int(inp()))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	a = []
	for i in range(n):
		if s[i] == '(':
			a.append(s[i])
		elif a:
			a.pop()
	print(len(a))


def correct(s):
	errors = 0
	while s[0] == ')':
		errors += 1
		s = s[1:]
	flag = 1
	while flag:
		counter = 0
		flag = 0
		for i in range(0, len(s)):
			if s[i] == '(':
				counter += 1
			else:
				counter -= 1
				if counter < 0:
					errors += 1
					flag = 1
					tmp = s
					s = tmp[0:i] + tmp[i + 1:]
					break
	return errors
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(correct(s))


for t in range(int(input())):
	n = int(input())
	v = [1 if c == '(' else -1 for c in list(input())]
	s = 0
	res = 0
	for e in v:
		if s + e == -1:
			res += 1
		else:
			s += e
	print(res)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	open = 0
	close = 0
	for ii in range(n):
		if s[ii] == '(':
			open += 1
		if s[ii] == ')' and open > close:
			close += 1
	print(open - close)


from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def solve():
	for _ in range(ii()):
		n = ii()
		s = si()
		cur = 0
		res = 0
		for i in range(n):
			if s[i] == ')':
				cur += 1
			else:
				cur -= 1
			if cur > 0:
				res += cur
				cur = 0
		print(res)
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
solve()


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
seti = set()
for i in range(40):
	seti.add(2 ** i)
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	ans = 0
	for i in range(n):
		if s[i] == ')':
			if stack == []:
				ans += 1
			else:
				stack.pop()
		else:
			stack.append('(')
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(o, c, cnt) = (0, 0, 0)
	for j in range(n):
		if s[j] == '(':
			o += 1
		elif s[j] == ')':
			c += 1
		if c > o:
			cnt += 1
			o = 0
			c = 0
	print(cnt)


T = int(input())
for i in range(0, T):
	n = int(input())
	S = str(input())
	ans = 0
	op = []
	for j in range(0, n):
		if S[j] == '(':
			op.append(j)
		else:
			l = len(op)
			if l != 0 and j > op[l - 1]:
				op.pop()
			else:
				ans += 1
	print(ans)


class CustomStack:

	def __init__(self):
		self.content = ''

	def push(self, char):
		if self.content == '':
			self.content += char
		elif self.content[-1] == '(' and char == ')':
			self.content = self.content[:-1]
		else:
			self.content += char

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		stack = CustomStack()
		c = str(input())
		for i in range(n):
			stack.push(c[i])
		print(min(stack.content.count('('), stack.content.count(')')))
main()


for _ in range(int(input())):
	k = int(input())
	n = input()
	c = 0
	for i in n:
		if i == '(':
			c = c + 1
		elif c > 0 and i == ')':
			c = c - 1
	print(c)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from copy import copy
from io import BytesIO, IOBase

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		ans = 0
		ct = 0
		for i in s:
			if i == '(':
				ans += 1
			else:
				ans -= 1
			if ans < 0:
				ans = 0
				ct += 1
		print(ct)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c1 = 0
	c2 = 0
	c3 = 0
	for j in range(n):
		if s[j] == '(':
			c1 = c1 + 1
		else:
			c2 = c2 + 1
		if c2 > c1:
			c3 = c3 + 1
			c2 = c2 - 1
	print(c3)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	a = 0
	b = 0
	c = 0
	val = 0
	ans = 0
	k = 0
	while True:
		val = 0
		a = 0
		b = 0
		while c != n:
			if s[c] == '(':
				a += 1
			else:
				b += 1
			if a >= b:
				pass
			else:
				val += 1
				s.append(s[c])
				del s[c]
				break
			c += 1
		ans += val
		if val == 0:
			break
	print(ans)


import math

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b / gcd(a, b)

def bs(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return arr[mid]
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def swap(list, pos1, pos2):
	(list[pos1], list[pos2]) = (list[pos2], list[pos1])
	return list
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = 0
	o = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			o += 1
		else:
			c += 1
		if c > o:
			c -= 1
			ans += 1
	print(ans)


t = int(input())

def case(n, s):
	c = 0
	balance = 0
	for i in range(n):
		f = True
		if s[i] == '(':
			balance += 1
		else:
			balance -= 1
		if balance < 0:
			balance += 1
			c += 1
	print(c)
for i in range(t):
	n = int(input())
	s = input()
	case(n, s)


for _ in range(int(input())):
	n = int(input())
	array = input()
	opening = 0
	closing = 0
	error = []
	result = 0
	for i in array:
		if i == '(':
			opening += 1
		else:
			closing += 1
		if closing > opening:
			result += 1
			closing = 0
			opening = 0
	print(result)


import sys
for _ in range(int(sys.stdin.readline())):
	n = int(sys.stdin.readline())
	brackets = sys.stdin.readline()
	c = s = 0
	for i in range(n):
		if brackets[i] == '(':
			s += 1
		elif brackets[i] == ')' and s != 0:
			s -= 1
		elif brackets[i] == ')' and s == 0:
			c += 1
	print(c)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = deque()
	for i in s:
		if i == '(':
			st.append(i)
		else:
			l = st.__len__()
			if l > 0:
				top = st.pop()
				if top == '(':
					continue
				st.append(top)
			st.append(i)
	print(st.__len__() // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	ar = input()
	bl = 0
	mbl = 0
	for i in ar:
		if i == ')':
			bl = bl + 1
		else:
			bl = bl - 1
		mbl = max(bl, mbl)
	print(mbl)


for test in range(int(input())):
	n = int(input())
	items = list(input())
	st = []
	for it in items:
		if it == ')':
			if st and st[-1] == '(':
				st.pop()
			else:
				st.append(')')
		else:
			st.append('(')
	print(st.count(')'))


for _ in range(int(input())):
	n = int(input())
	a = input()
	(w, c) = (0, 0)
	for x in range(n):
		if a[x] == '(':
			w += 1
		elif w > 0:
			w -= 1
		else:
			c += 1
	print(c)


for i in range(int(input())):
	n = int(input())
	st = input()
	close = 0
	open = 0
	for ele in st:
		if ele == '(':
			open += 1
		elif ele == ')' and open > 0:
			open -= 1
		else:
			close += 1
	print(close)


t = int(input())
while t > 0:
	length = int(input())
	string = input()
	(count, ans) = (0, 0)
	for bracket in string:
		if bracket == '(':
			count += 1
		elif count > 0:
			count -= 1
		else:
			ans += 1
	print(ans)
	t -= 1


import sys
import math
import operator as op
from functools import reduce
from bisect import *
from collections import OrderedDict
from collections import deque

def read_line():
	return sys.stdin.readline()[:-1]

def read_int():
	return int(sys.stdin.readline())

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def read_float_line():
	return [float(v) for v in sys.stdin.readline().split()]

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer / denom

def index(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return i
	return -1

def find_lt(a, x):
	i = bisect_left(a, x)
	if i:
		return i - 1
	return -1

def find_le(a, x):
	i = bisect_right(a, x)
	if i:
		return i - 1
	return -1

def find_gt(a, x):
	i = bisect_right(a, x)
	if i != len(a):
		return i
	return -1

def find_ge(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	return -1
mod = int(1000000000.0) + 7
mod2 = 998244353
t = read_int()
for i in range(t):
	n = read_int()
	s = read_line()
	cnt = 0
	o = 0
	c = 0
	for i in s:
		if i == '(':
			o += 1
		else:
			c += 1
		if c > o:
			cnt += c - o
			c = 0
			o = 0
	print(abs(cnt))


def a():
	n = int(input())
	itr = input()
	arr = []
	count = 0
	for i in range(n):
		if arr == []:
			arr.append(itr[i])
		elif arr[-1] == '(' and itr[i] == ')':
			arr.pop()
		else:
			arr.append(itr[i])
	if arr == []:
		print(0)
	else:
		print(len(arr) // 2)
t = int(input())
for i in range(t):
	a()


t = int(input())
for x in range(t):
	n = int(input())
	s = str(input())
	total = 0
	flip = 0
	for i in range(n):
		if s[i] == '(':
			flip = flip + 1
		else:
			flip = flip - 1
		if flip < 0:
			total = total + 1
			flip = 0
	print(total)


t = int(input())
for z in range(t):
	n = int(input())
	s = input()
	count = 0
	arr = []
	for i in range(n):
		if s[i] == '(':
			arr.append(1)
			continue
		if s[i] == ')':
			if len(arr) != 0:
				arr.pop()
			else:
				count = count + 1
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	c = 0
	l = []
	for i in range(n):
		if s[i] == '(':
			l.append('(')
		elif len(l) != 0 and s[i] == ')':
			l.pop()
			c += 1
	print((n - c * 2) // 2)


p = int(input())
for i in range(p):
	n = int(input())
	s = input()
	stek = []
	ans = 0
	for i in range(n):
		if s[i] == '(':
			stek.append('(')
		elif len(stek) != 0:
			stek.pop(-1)
		else:
			ans += 1
	print(ans)


for i in range(int(input())):
	n = int(input())
	a = input()
	temp = 0
	tot = 0
	for i in a:
		if i == '(':
			temp += 1
		if i == ')':
			temp -= 1
		tot = min(temp, tot)
	print(abs(tot))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input()
	b = ans = 0
	for x in s:
		if x == ')':
			ans += b == 0
			b = max(b - 1, 0)
		else:
			b += 1
	print(ans)


t = int(input())
l = list()
for i in range(t):
	n = int(input())
	s = input()
	while s.count('()') != 0:
		s = s.replace('()', '')
	l.append(len(s) // 2)
for i in l:
	print(i)


import sys
from math import sqrt
input = sys.stdin.readline

def inp():
	return int(input())

def inlist():
	return list(map(int, input().split()))

def instr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def main():
	t = inp()
	for l in range(t):
		n = inp()
		s = instr()
		(a, x) = (0, 0)
		for i in range(n):
			if s[i] == '(':
				x += 1
			else:
				x -= 1
			if x < 0:
				x = 0
				a += 1
		print(a)
main()


n = int(input())
arr = []
for i in range(n):
	a = int(input())
	brackets = list(input())
	k = 0
	t = 0
	j = 0
	while j < len(brackets):
		if brackets[j] == '(':
			k += 1
		else:
			k -= 1
		if k < 0:
			t += 1
			brackets.pop(j)
			brackets.append(')')
			k += 1
		else:
			j += 1
	arr.append(t)
for i in arr:
	print(i)


for _ in range(int(input())):
	input()
	good = 0
	bad = 0
	for i in input():
		if i == '(':
			good += 1
		elif good > 0:
			good -= 1
		else:
			bad += 1
	print(bad)


T = int(input())
for _ in range(T):
	n = int(input())
	s = list(input())
	count = 0
	for i in s:
		if i == '(':
			count += 1
		if i == ')' and count > 0:
			count -= 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	brackets = list(input())
	shit = 0
	ans = 0
	for i in brackets:
		if i == '(':
			shit += 1
		else:
			shit -= 1
		if shit < 0:
			shit = 0
			ans += 1
	print(ans)


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	s = inp()
	ans = 0
	counter = 0
	maxCounter = 0
	for i in s:
		if i == ')':
			counter -= 1
			if counter < maxCounter:
				ans += 1
			maxCounter = min(maxCounter, counter)
		else:
			counter += 1
	print(ans)


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(sys.stdin.readline())
	s = list(sys.stdin.readline().strip())
	list_check = [0] * n
	list_satck = []
	for i in range(n):
		if s[i] == '(':
			list_satck.append(i)
			break
	count = n
	for i in range(i + 1, n):
		if s[i] == '(':
			list_satck.append(i)
		elif list_satck:
			list_satck.pop()
			n -= 2
	print(n // 2)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	for _ in range(ii()):
		n = ii()
		s = si()
		f = 0
		x = 0
		for i in range(n):
			if s[i] == '(':
				x += 1
			else:
				x -= 1
			if x < 0:
				f += 1
				x = 0
		print(f)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
for i in range(n):
	st = int(input())
	s = input()
	c = 0
	mn = 0
	for i in range(len(s)):
		if s[i] == '(':
			c += 1
		else:
			mn = min(mn, c - 1)
			c -= 1
	print(abs(mn))


def areParanthesisBalanced(expr):
	stack = []
	c = 0
	for char in expr:
		if char == '(':
			stack.append(char)
		else:
			if not stack:
				c = c + 1
			if len(stack) > 0:
				current_char = stack.pop()
				if current_char == '(':
					if char != ')':
						c = c + 1
	print(c)
n = int(input())
for i in range(n):
	a = int(input())
	b = input()
	areParanthesisBalanced(b)


t = int(input())
testcases = [(int(input()), input()) for _ in range(t)]
for tup in testcases:
	(n, s) = tup
	k = ck = 0
	for b in s:
		if b == '(':
			ck += 1
		else:
			ck -= 1
			if ck == -1:
				k += 1
				ck = 0
			else:
				pass
	print(k)


z = input
from math import ceil, log, gcd
n1 = int(z())
for _ in range(n1):
	c = ans = 0
	z()
	l = []
	for i in input():
		if i == '(':
			l.append(i)
		elif i == ')' and len(l) > 0:
			l.pop()
		else:
			c += 1
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	res = 0
	open_bracket = 0
	for i in range(n):
		if s[i] == '(':
			open_bracket += 1
		elif open_bracket == 0:
			res += 1
		else:
			open_bracket -= 1
	print(res)


import sys
import math
from collections import defaultdict

def solve(test):
	n = int(input())
	s = input()
	(op, cl) = (0, 0)
	for c in s:
		if c == ')':
			if op > 0:
				op -= 1
			else:
				cl += 1
		else:
			op += 1
	print((op + cl) // 2)
test_cases = int(input())
for t in range(1, test_cases + 1):
	solve(t)


for _ in range(int(input())):
	n = input()
	s = input()
	balance = 0
	ans = 0
	a = []
	for c in s:
		if c == '(':
			a.append(c)
		elif len(a) > 0 and a[-1] == '(':
			a.pop()
		else:
			a.append(c)
	print(len(a) // 2)


GI = lambda : int(input())
GIS = lambda : map(int, input().split())
LGIS = lambda : list(GIS())

def main():
	for t in range(GI()):
		GI()
		s = input()
		opening = misplaced_closing = 0
		for c in s:
			if c == '(':
				opening += 1
			elif opening == 0:
				misplaced_closing += 1
			else:
				opening -= 1
		print(misplaced_closing)
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	a = 0
	b = 0
	coun = 0
	for i in s:
		if i == '(':
			a += 1
		elif i == ')':
			b += 1
			if b > a:
				b -= 1
				coun += 1
	print(coun)


for _ in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	from collections import deque
	d = deque()
	for i in range(n):
		if s[i] == '(':
			d.append(s[i])
		elif len(d) > 0:
			if d[-1] == '(':
				d.pop()
			else:
				d.append(s[i])
				count += 1
		else:
			d.append(s[i])
			count += 1
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	lol = list(s)
	ope = 0
	ans = 0
	for i in range(len(lol)):
		if lol[i] == '(':
			ope += 1
		else:
			ope -= 1
			if ope < 0:
				ope = 0
				ans += 1
	print(ans)


for _ in [*open(0)][2::2]:
	a = 0
	b = 0
	for x in _:
		b += 2 * ord(x) - 81
		a += b > a
	print(a)


import sys
from collections import deque

def get_ints():
	return map(int, I().strip().split())

def get_list():
	return list(map(int, I().strip().split()))
I = sys.stdin.readline
for _ in range(int(I())):
	n = int(I())
	a = I()
	stack = deque()
	for i in range(n):
		if a[i] == '(':
			stack.append(a[i])
		elif len(stack) > 0:
			temp = stack.pop()
			if temp != a[i]:
				continue
			else:
				stack.append(temp)
				stack.append(a[i])
		else:
			stack.append(a[i])
	print(len(stack) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ap = 0
	for i in s:
		if i == '(':
			ap += 1
		elif i == ')' and ap > 0:
			ap -= 1
	print(ap)


T = int(input().rstrip())
for tt in range(T):
	n = int(input().rstrip())
	st = input().rstrip()
	stk = []
	cnt = 0
	for i in st:
		if i == '(':
			stk.append(i)
		elif len(stk) > 0:
			stk.pop()
		else:
			cnt += 1
	print(cnt)


for _ in range(int(input())):
	length = int(input())
	brackets = input()
	found = True
	while found:
		found = False
		j = 0
		while j < len(brackets) - 1:
			if brackets[j] == '(' and brackets[j + 1] == ')':
				found = True
				brackets = brackets[:j] + brackets[j + 2:]
				j += 2
			else:
				j += 1
	print(len(brackets) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	f = 0
	c = 0
	for i in s:
		if f == 0 and i == ')':
			c += 1
			continue
		if i == '(':
			f += 1
		else:
			f -= 1
	print(c)


for _ in range(int(input())):
	n = int(input())
	string = input()
	ans = 0
	x2 = 0
	for i in range(n):
		if string[i] == ')':
			if x2 == 0:
				ans += 1
			else:
				x2 -= 1
		elif string[i] == '(':
			x2 += 1
	print(ans)


import sys
tc = int(sys.stdin.readline())
for _ in range(tc):
	n = int(sys.stdin.readline())
	arr = list(sys.stdin.readline().rstrip())
	st = []
	for i in range(n):
		if arr[i] == '(':
			st.append(arr[i])
		else:
			rem = False
			if st:
				if st[-1] == '(':
					st.pop()
					rem = True
			if not rem:
				st.append(arr[i])
	print(len(st) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ope = 0
	clo = 0
	totc = 0
	toto = 0
	for i in s:
		if i == '(':
			ope += 1
		elif i == ')':
			if ope > 0:
				ope -= 1
			else:
				clo += 1
	print(ope)


from sys import stdin
a = int(stdin.readline())
for i in range(0, a):
	n = int(stdin.readline())
	brack = list(stdin.readline().rstrip())
	add = 0
	count = 0
	for j in brack:
		if j == '(':
			add += 1
		elif j == ')':
			add -= 1
		if add < 0:
			add += 1
			count += 1
	print(count)


import sys
t = int(input())
while t:
	n = int(input()) // 2
	s = sys.stdin.readline().strip()
	while n:
		s = s.replace('()', '')
		n -= 1
	print(len(s) // 2)
	t -= 1


import sys
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()

def print(*argv):
	fast_writer(' '.join((str(i) for i in argv)))
	fast_writer('\n')
for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			ans += 1
			c = 0
	print(ans)


def test(n, s):
	count = 0
	unpos = 0
	for i in s:
		if i == '(':
			count += 1
		elif i == ')':
			count -= 1
		if count < 0:
			unpos += 1
			count = 0
	return unpos
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(test(n, s))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	count = 0
	count1 = 0
	for j in range(len(s)):
		if s[j:j + 1] == '()':
			j = j + 1
		elif s[j] == ')':
			if count1 > 0:
				count1 -= 1
			else:
				count += 1
		elif s[j] == '(':
			count1 += 1
	print(count)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	stack = 0
	res = 0
	for i in s:
		if i == '(':
			stack += 1
		else:
			if stack < 1:
				res += 1
				continue
			stack -= 1
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	cnt = 0
	result = 0
	for i in range(len(s)):
		if s[i] == '(':
			cnt += 1
		else:
			cnt -= 1
			if cnt < 0:
				cnt = 0
				result += 1
	print(result)


from collections import deque

def ans(n, string):
	stack = deque()
	for i in string:
		if not stack:
			stack.append(i)
		elif i == ')' and stack[-1] == '(':
			stack.pop()
		else:
			stack.append(i)
	return len(stack) // 2
t = int(input())
for _ in range(t):
	n = int(input())
	string = str(input())
	print(ans(n, string))


from sys import stdin, exit
input = stdin.readline

def i():
	return input()

def ii():
	return int(input())

def iis():
	return map(int, input().split())

def liis():
	return list(map(int, input().split()))

def print_array(a):
	print(' '.join(map(str, a)))
t = ii()
for _ in range(t):
	n = int(input())
	s = input()[:-1]
	a = []
	for c in s:
		if len(a) and a[-1] == '(' and (c == ')'):
			a.pop()
		else:
			a.append(c)
	print(len(a) // 2)


n = int(input())
for i in range(n):
	k = int(input())
	s = input()
	min = 0
	count = 0
	for i in range(len(s)):
		if s[i] == '(':
			count += 1
		else:
			count -= 1
		if count < min:
			min = count
	print(abs(min))


t = int(input())
for i in range(t):
	x = int(input())
	n = input()
	count = 0
	minimum = 0
	for j in n:
		if j == '(':
			count += 1
		else:
			count -= 1
		minimum = min(minimum, count)
	print(abs(minimum))


n = int(input())
for i in range(n):
	p = int(input())
	k = input()
	lst = []
	count = 0
	for i in k:
		if i == '(':
			lst.append('(')
		elif len(lst) == 0:
			count = count + 1
		else:
			lst.pop()
	print(count)


for _ in range(int(input())):
	_ = int(input())
	b = input()
	c = 0
	for s in b:
		if s == '(':
			c += 1
		elif s == ')':
			c = max(0, c - 1)
	print(c)


Q = int(input())
for i in range(Q):
	N = int(input())
	S = input()
	Min = 0
	cnt = 0
	for j in range(N):
		if S[j] == '(':
			cnt += 1
		else:
			cnt -= 1
			if Min > cnt:
				Min = cnt
	print(-Min)


def fun(s):
	c = 0
	l = []
	for i in range(n):
		if s[i] == '(':
			l.append(s[i])
		elif len(l) == 0:
			c += 1
		else:
			l.remove('(')
	return c
t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip()
	print(fun(s))


import math

def main():
	t = Iint()
	for _ in range(t):
		n = Iint()
		s = I()
		ans = 0
		stack_size = 0
		for si in s:
			if si == '(':
				stack_size += 1
			elif si == ')':
				stack_size -= 1
			if stack_size == -1:
				ans += 1
				stack_size = 0
		print(ans)
FIO = True

def I():
	return input()

def Iint():
	return int(input())

def Ilist():
	return list(map(int, input().split()))

def Imap():
	return map(int, input().split())

def Plist(li, s=' '):
	print(s.join(map(str, li)))
if FIO:
	from io import BytesIO, IOBase
	import sys
	import os
en = enumerate
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


def move_brackets(s):
	moves = 0
	for i in s:
		if i == '(':
			moves += 1
		elif i == ')' and moves > 0:
			moves -= 1
	return moves
t = int(input())
for t_itr in range(t):
	n = int(input())
	s = str(input())
	result = move_brackets(s)
	print(result)


for t in range(int(input())):
	n = int(input())
	s = [x for x in input()]
	op = 0
	cl = 0
	i = 0
	moves = 0
	while i < n:
		if s[i] == ')' and cl + 1 > op:
			s.append(s.pop(i))
			moves += 1
			continue
		if s[i] == ')':
			cl += 1
		else:
			op += 1
		i += 1
	print(moves)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = s.count('(')
	(l, r) = (0, c + 1)
	while r - l > 1:
		m = (l + r) // 2
		idx = 0
		d = c - m
		for i in range(n):
			if s[i] == '(':
				if idx < m:
					d += 1
					idx += 1
			else:
				d -= 1
			if d < 0:
				r = m
				break
		else:
			l = m
	print(c - l)


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	start = []
	c = 0
	for i in range(n):
		if s[i] == '(':
			start.append(s[i])
		elif start == []:
			c = c + 1
		else:
			start.pop(-1)
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s = s[:s.index('()')] + s[s.index('()') + 2:]
	print(s.count('('))


n = int(input())
for i in range(n):
	_ = input()
	s = input()
	a = 0
	b = 0
	d = 0
	for c in s:
		if c == '(':
			a += 1
		else:
			b += 1
		if b > a:
			d += 1
			b -= 1
	print(d)


from math import *
from collections import deque
from copy import deepcopy
import sys

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def multi():
	return map(int, input().split())

def strmulti():
	return map(str, inp().split())

def lis():
	return list(map(int, inp().split()))

def lcm(a, b):
	return a * b // gcd(a, b)

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def stringlis():
	return list(map(str, inp().split()))

def out(var):
	sys.stdout.write(str(var))

def printlist(a):
	print(' '.join((str(a[i]) for i in range(len(a)))))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
t = int(input())
for j in range(t):
	n = int(input())
	s = str(inp())
	ans = 0
	temp = 0
	for i in s:
		if i == '(':
			temp += 1
		else:
			temp -= 1
		ans = min(ans, temp)
	print(-ans)


T = int(input().strip())
for t in range(T):
	n = int(input().strip())
	arr = input().strip()
	run_count = 0
	ans = 0
	for i in arr:
		if ans < -1 * run_count:
			ans = -1 * run_count
		if i == '(':
			run_count += 1
		else:
			run_count -= 1
	print(ans)


t = int(input())
for _ in range(t):
	res = 0
	n = int(input())
	s = str(input())
	bal = 0
	for i in range(len(s)):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				res += 1
	print(res)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def solution(s, n):
	bal = 0
	end = []
	for i in range(n):
		x = s[i]
		if x == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			end.append(i)
			bal = 0
	return len(end)

def main():
	T = 1
	T = ri()
	for i in range(T):
		n = ri()
		s = rs()
		x = solution(s, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


import math
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	sum = 0
	sum1 = 0
	for z in range(n):
		if s[z] == '(':
			sum = sum + 1
		elif sum > 0:
			sum = sum - 1
		else:
			sum1 = sum1 + 1
	print(sum1)


def f(s):
	co = 0
	cc = 0
	minn = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == ')':
			cc = cc + 1
		else:
			co = co + 1
		minn = min(minn, cc - co)
	return abs(minn)
for tc in range(int(input())):
	_ = input()
	s = input()
	print(f(s))


def countbraces(S):
	while len(S) > 0:
		if '()' in S:
			temp = S.replace('()', '')
			S = temp
		else:
			return int(len(S) / 2)
	if len(S) == 0:
		return 0
t = int(input())
if t >= 1 and t <= 2000:
	N = list()
	A = list()
	for i in range(t):
		N.append(int(input()))
		A.append(input())
	for i in range(t):
		if N[i] >= 2 and N[i] <= 50:
			print(countbraces(A[i]))


t = int(input())
while t:
	a = int(input())
	s = input()
	ans = a // 2
	start = []
	cnt = 0
	for i in range(len(s)):
		if s[i] == '(':
			start.append(s[i])
		elif start == []:
			cnt += 1
		else:
			start.pop(-1)
	print(cnt)
	t -= 1


t = int(input())
for i in range(t):
	_ = int(input())
	s = input()
	abiertos = 0
	moves = 0
	for c in s:
		if c == '(':
			abiertos += 1
		elif abiertos <= 0:
			moves += 1
			abiertos = 0
		else:
			abiertos -= 1
	print(moves)


for _ in range(int(input())):
	m = int(input())
	st = input()
	stack = []
	c = 0
	for i in range(m):
		if len(stack) == 0 and st[i] == ')':
			c += 1
		elif len(stack) == 0 and st[i] == '(':
			stack.append(st[i])
		elif len(stack) != 0:
			if st[i] == '(':
				stack.append(st[i])
			elif st[i] == ')':
				stack.pop()
	print(c)


def order_brackets(s):
	o = 0
	c = 0
	nan = 0
	for i in s:
		if i == ')':
			if o > 0:
				o -= 1
			else:
				c += 1
		else:
			o += 1
	print(o)
t = int(input())
for i in range(t):
	n = input()
	s = input()
	order_brackets(s)


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = [s[0]]
	ans = 0 if s[0] == '(' else 1
	for i in range(1, n):
		if s[i] == '(':
			st.append(s[i])
		else:
			if st:
				if st[-1] == '(':
					st.pop(-1)
					continue
			st.append(s[i])
			ans += 1
	print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		s = S()
		t = 0
		r = 0
		for c in s:
			if c == '(':
				t += 1
			else:
				t -= 1
				if t < 0:
					r += 1
					t = 0
		rr.append(r)
	return JA(rr, '\n')
print(main())


q = int(input())
for i in range(q):
	n = int(input())
	ch = input()
	k = 0
	ans = 0
	for i in range(n):
		if ch[i] == '(':
			k += 1
		elif k == 0:
			ans += 1
			k = 0
		else:
			k -= 1
	ans += k
	print(ans // 2)


def solve(n, s):
	wrong = 0
	o = 0
	c = 0
	k = 1
	while k == 1:
		if '()' in s:
			s = s[:s.index('()')] + s[s.index('()') + 2:]
		else:
			k = 0
	return s.count(')')
t = int(input())
for we in range(t):
	n = int(input())
	s = input()
	print(solve(n, s))


t = int(input())
while t > 0:
	n = int(input())
	s = list(str(input()))
	ob = 0
	cb = 0
	i = 0
	trans = 0
	while i < n:
		if s[i] == '(':
			if cb > ob:
				trans += 1
				l = s[:i]
				if i != n - 1:
					s = l + s[i + 1:]
				s.insert(0, '(')
			ob += 1
			i = i + 1
		elif ob < cb + 1:
			trans += 1
			l = s[:i]
			if i != n - 1:
				s = l + s[i + 1:]
			s.append(')')
		else:
			cb += 1
			i = i + 1
	print(trans)
	t = t - 1


import math
import collections
import sys

def inpu():
	return input().split(' ')

def inti(a):
	for i in range(len(a)):
		a[i] = int(a[i])
	return a

def inp():
	a = inpu()
	a = inti(a)
	return a
for _ in range(int(input())):
	n = int(input())
	a = input()
	arr = [0] * n
	count = 0
	for i in range(n):
		if a[i] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			arr[i] = count
	i = 0
	val = 0
	ans = 0
	while i < n:
		if arr[i] + val < 0 and a[i] == ')':
			ans += 1
			val += 1
		i += 1
	print(ans)


from sys import stdin, stdout
import heapq as hq
from collections import defaultdict
t = int(input())
for tc in range(t):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	l = 0
	res = 0
	for c in s:
		if c == '(':
			l += 1
		elif l > 0:
			l -= 1
		else:
			res += 1
	stdout.write(str(res) + '\n')


from sys import stdin, stdout
test = int(stdin.readline())
for _ in range(test):
	N = int(stdin.readline())
	s = stdin.readline().strip()
	st = []
	wrong_close = 0
	wrong_open = 0
	for i in s:
		if i == '(':
			st.append(1)
		if i == ')':
			if len(st) == 0:
				wrong_close += 1
			else:
				st.pop()
	wrong_open = len(st)
	print(min(wrong_close, wrong_open))


t = int(input())
for t in range(t):
	n = int(input())
	s = input()
	offset = 0
	for i in range(n):
		if s[i] == '(':
			offset += 1
		if s[i] == ')':
			if offset > 0:
				offset -= 1
	print(offset)


def main():
	t = int(input())
	for _ in range(t):
		x = int(input())
		s = input()
		valmin = 30
		count = 0
		for i in range(x):
			count += 1 if s[i] == '(' else -1
			valmin = count if valmin > count else valmin
		print(abs(valmin))
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	a = []
	c = 0
	count = 0
	for j in range(n):
		if s[j] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			c = 0
			count += 1
	print(count)


a = int(input())
for i in range(a):
	x = int(input())
	st = input()
	temp = 0
	res = 0
	while 0 != len(st):
		temp = len(st)
		st = st.replace('()', '')
		if temp == len(st):
			st = st[1:] + st[0]
			res += 1
	print(res)


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	arr = []
	p = 0
	for i in range(n):
		if string[i] == ')':
			if len(arr) == 0:
				p += 1
			elif len(arr) >= 1 and arr[-1] == '(':
				arr.pop()
		else:
			arr.append(string[i])
	print(p)


N = int(input())
for _ in range(N):
	n = int(input())
	brak = input().strip()
	st = []
	ct = 0
	for i in brak:
		if i == ')':
			if len(st):
				st.pop()
			else:
				ct += 1
		elif i == '(':
			st.append(i)
	print(ct)


for _ in range(int(input())):
	l = n = int(input())
	s = input()
	count = ans = 0
	for i in range(l):
		if s[i] == '(':
			count += 1
		elif s[i] == ')':
			count -= 1
		if count < 0:
			s = s[i] + s[0:i] + s[i + 1:n] + s[i]
			l -= 1
			count = 0
			ans += 1
	print(ans)


t = int(input())
while t > 0:
	arr = []
	a = 0
	n = int(input())
	temp = str(input())
	for i in range(0, n):
		if temp[i] == '(':
			arr.append('(')
		elif len(arr) == 0:
			a += 1
		else:
			arr.pop()
	print(a)
	t = t - 1


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	r = 0
	w = 0
	for i in range(len(s)):
		if s[i] == ')':
			if r == 0:
				w += 1
			else:
				r -= 1
		elif s[i] == '(':
			r += 1
	print(abs(r))


for _ in range(int(input())):
	n = int(input())
	(o, c) = (0, 0)
	for i in input():
		if i == ')':
			if o != 0:
				o -= 1
			else:
				c += 1
		else:
			o += 1
	print(c)


for _ in range(int(input())):
	input()
	x = y = 0
	for ch in input():
		x += (-1, 1)[ch == '(']
		y = min(x, y)
	print(-y)


t = int(input())
for _ in range(t):
	st = 0
	res = 0
	input()
	s = input()
	for i in s:
		if i == '(':
			st += 1
		else:
			st -= 1
		if st == -1:
			res += 1
			st += 1
	print(res)


import math
from collections import *
import sys
from functools import reduce

def get_ints():
	return map(int, input().strip().split())

def get_list():
	return list(get_ints())

def getlistofstring():
	return list(input().strip().split())

def printxsp(*args):
	return print(*args, end='')

def printsp(*args):
	return print(*args, end=' ')
UGLYMOD = int(1000000000.0) + 7
SEXYMOD = 998244353
MAXN = int(100000.0)
for _testcases_ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	for i in s:
		if len(stack) > 0:
			if i == ')' and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(i)
		else:
			stack.append(i)
	print(len(stack) // 2)


def find(s):
	li = []
	count = 0
	for i in s:
		if i == '(':
			li.append(i)
		if len(li) == 0 and i == '(':
			li.append(i)
		elif len(li) == 0 and i == ')':
			count = count + 1
		elif li[-1] == '(' and i == ')':
			li.pop()
	if count == 0:
		print(0)
	else:
		print(count)
n = int(input())
for i in range(0, n):
	x = int(input())
	s = str(input())
	find(s)


for test in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	while s[0] == ')':
		s = s[:0] + s[1:] + ')'
		ans += 1
	ok = 0
	i = 0
	while True:
		i -= 1
		while ok >= 0 and i < n - 1:
			i += 1
			if s[i] == '(':
				ok += 1
			else:
				ok -= 1
		if i < n - 1:
			s = s[:i] + s[i + 1:] + ')'
			ans += 1
			ok = 0
		else:
			break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = [s[0]]
	c = 0
	for i in range(1, n):
		if len(l) > 0:
			if l[-1] == '(' and s[i] == ')':
				l.pop(-1)
			else:
				l.append(s[i])
		else:
			l.append(s[i])
	print(len(l) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	st = []
	for i in a:
		if i == '(':
			st.append(i)
		elif i == ')' and (st == [] or st[-1] == ')'):
			st.append(i)
		else:
			st.pop(-1)
	c0 = 0
	c1 = 1
	for i in st:
		if i == '(':
			c0 += 1
		else:
			c1 += 1
	print(c0)


T = int(input().rstrip())

def solve(k):
	num_open = 0
	num_good = 0
	for c in k:
		if c == '(':
			num_open += 1
		elif num_open >= 1:
			num_good += 2
			num_open -= 1
	print(int((len(k) - num_good) / 2))
for test in range(T):
	x = int(input().rstrip())
	combo = input().rstrip()
	ans = solve(combo)


for i in range(int(input())):
	n = int(input())
	x = input()
	cnt_ones = cnt_zeros = res = 0
	for j in range(n):
		if x[j] == '(':
			cnt_ones += 1
		elif cnt_zeros < cnt_ones:
			cnt_zeros += 1
		else:
			res += 1
	print(res)


def function(N, lineup):
	checker = 0
	ans = 0
	for i in range(N):
		if checker < 0:
			ans += 1
			checker = 0
		if lineup[i] == '(':
			checker += 1
		else:
			checker -= 1
	return ans
for i in range(int(input())):
	N = int(input())
	lineup = list(input())
	print(function(N, lineup))


for _ in range(0, int(input())):
	n = int(input())
	l = list(input().strip())
	flag = 0
	prob_left = 0
	prob_right = 0
	ok = 0
	for i in range(0, n):
		if flag == 0:
			if l[i] == '(':
				flag = 1
				ok += 1
			else:
				prob_right += 1
		else:
			if l[i] == '(':
				ok += 1
			else:
				ok -= 1
			if ok == -1:
				prob_right += 1
				ok = 0
	print(prob_right)


import sys
import math
import collections

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_input():
	return list(map(int, input().split()))
t = int(input())
for ti in range(1, t + 1):
	n = int(input())
	s = input()
	l = 0
	for x in s:
		if x == '(':
			l += 1
		elif l > 0:
			l -= 1
	print(l)


import sys
input = lambda : sys.stdin.readline().strip()
li = lambda : list(map(int, input().split()))
I = lambda : int(input())
for _ in range(I()):
	n = I()
	s = input()
	stack = []
	i = 0
	while i < n:
		if s[i] == '(':
			stack.append('(')
		if s[i] == ')' and len(stack) != 0 and (stack[-1] == '('):
			stack.pop()
		elif s[i] == ')':
			stack.append(')')
		i += 1
	print(len(stack) // 2)


for _ in range(int(input())):
	n = int(input())
	skobs = input()
	check = [False] * n
	for i in range(n):
		pair = False
		if skobs[i] == '(':
			for j in range(i + 1, n):
				if skobs[j] == ')' and (not check[j]):
					check[j] = True
					pair = True
					break
			if pair:
				check[i] = True
	print(check.count(False) // 2)


for i in range(int(input())):
	n = int(input())
	s = input()
	p = 0
	mi = 0
	for i in range(n):
		if s[i] == ')':
			p -= 1
		else:
			p += 1
		if p < mi:
			mi = p
	print(abs(mi))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	cnt = 0
	net = 0
	for j in range(n):
		if s[j] == '(':
			net += 1
		elif net <= 0:
			cnt += 1
		else:
			net -= 1
	print(cnt)


t = int(input())
for i in range(t):
	n = int(input())
	val = str(input())
	count = 0
	moves = 0
	for i in range(0, n):
		if val[i] == '(':
			count = count + 1
		elif val[i] == ')':
			if count >= 1:
				count = count - 1
			else:
				while val[i] == ')' and count < 1:
					moves = moves + 1
					val = val[0:i] + val[i + 1:] + ')'
				if val[i] == '(':
					count = count + 1
				elif val[i] == ')':
					count = coint - 1
	print(moves)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(input())
	cur = 0
	ans = 0
	for i in a:
		if i == ')':
			cur -= 1
		else:
			cur += 1
		ans = min(ans, cur)
	print(-ans)


for x in range(int(input())):
	n = int(input())
	s = input()
	no = 0
	count = 0
	for x in s:
		if x == '(':
			no += 1
		elif no > 0:
			no -= 1
		else:
			count += 1
	print(count)


for i in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	if s != '':
		print(len(s) // 2)
	else:
		print(0)


import math
from collections import deque
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 2
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	result.append(n)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < abs(max_ending_here):
			max_so_far = max_ending_here
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	n = int(input())
	s = input()
	c = 0
	l = []
	for j in range(0, n):
		if s[j] == '(':
			l.append(s[j])
		elif len(l) == 0:
			c += 1
		else:
			l.pop()
	print(c)
t = int(input())
for i in range(0, t):
	main()


import sys
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
for _ in range(ii1()):
	n = ii1()
	s = is1()
	stack = []
	for i in s:
		if i == '(':
			stack.append(i)
		elif stack:
			if stack[-1] == '(':
				stack.pop()
			else:
				stack.append(i)
		else:
			stack.append(i)
	n = len(stack) // 2
	print(n)


for u in range(int(input())):
	n = int(input())
	s = input()
	l = []
	c = 0
	for i in range(n):
		if l == [] and s[i] == ')':
			c += 1
		elif s[i] == '(':
			l.append('(')
		elif s[i] == ')':
			l.pop()
	print(c)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = 0
	k = 0
	for j in range(n):
		if a[j] == ')' and b == 0:
			k += 1
		elif a[j] == ')' and b >= 0:
			b -= 1
		elif a[j] == '(':
			b += 1
	print(k)


t = int(input())
for i in range(t):
	l = []
	n = int(input())
	s = str(input())
	for i in s:
		if i == ')':
			if '(' not in l:
				l.append(i)
			else:
				l.pop()
		if i == '(':
			l.append(i)
	print(len(l) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	str = input()
	while str.find('()') != -1:
		str = str.replace('()', '')
	count = 0
	for symbol in str:
		if symbol == '(':
			count += 1
	print(count)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	k = 0
	b = 0
	for i in range(n):
		if s[i] == '(':
			k = k + 1
		else:
			k = k - 1
			if k == -1:
				k = 0
				b = b + 1
	t = t - 1
	print(b)


for _ in [0] * int(input()):
	n = int(input())
	b = input()
	while '()' in b:
		b = b.replace('()', '')
	print(len(b) // 2)


def C(seq):
	count = 0
	for i in seq:
		if i == '(':
			count += 1
		elif count > 0:
			count -= 1
	print(count)
a = int(input())
for _ in range(a):
	b = input()
	c = str(input())
	C(c)


n = int(input())
for j in range(n):
	st = int(input())
	s = input()
	str = []
	for i in s:
		str.append(i)
	i = 0
	count = 0
	temp = 0
	while True:
		if str[i] == ')':
			temp -= 1
		else:
			temp += 1
		if temp < 0:
			count += 1
			temp = 0
			a = str[i]
			del str[i]
			str.append(a)
			i = i - 1
		if len(str) - 1 == i:
			break
		i = i + 1
	print(count)


t = int(input())
while t > 0:
	n = int(input())
	s = input().strip()
	bkts = []
	for x in s:
		if x == '(':
			bkts.append(x)
		elif len(bkts) == 0:
			bkts.append(x)
		elif bkts[-1] == '(':
			bkts.pop()
		else:
			bkts.append(x)
	moves = len(bkts) // 2
	print(moves)
	t = t - 1


from copy import copy, deepcopy

def read_int():
	return int(input())

def read_arr():
	return [int(x) for x in input().split(' ')]

def read_mx(n, m):
	return [[int(num) for num in input().split(' ')] for _ in range(0, n)]

def work(p_case):
	n = read_int()
	br = input()
	balance = 0
	mn = 0
	for c in br:
		mn = min(mn, balance)
		if c in '(':
			balance += 1
		else:
			balance -= 1
	print(-mn)
t = read_int()
for case in range(0, t):
	work(case + 1)


for i in range(int(input())):
	n = int(input())
	s = input()
	b = 0
	ans = 0
	for i in s:
		if i == '(':
			if b >= 0:
				b += 1
			else:
				ans += abs(b)
				b = 1
		else:
			b -= 1
	print(ans)


import sys
input = sys.stdin.readline
numOfcase = int(input())
for _ in range(numOfcase):
	length = int(input())
	pare = list(input())
	check = 0
	cnt = 0
	for i in range(length):
		if pare[i] == '(':
			check += 1
		else:
			check -= 1
		if check < 0:
			cnt += 1
			check = 0
	print(cnt)


for t in range(int(input())):
	n = int(input())
	s = list(input().strip())
	c = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
			if c < 0:
				c = 0
				ans += 1
	print(ans)


n = int(input())
for i in range(n):
	a = int(input())
	s = input()
	while s.find('()') != -1:
		s = s.split('()')
		s = ''.join(s)
	print(int(len(s) / 2))


for _ in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	z = 0
	for i in s:
		if i == ')':
			count -= 1
		if count < 0:
			z = min(z, count)
		if i == '(':
			count += 1
	print(abs(z))


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	operations = 0
	index = 0
	openings = 0
	while index < n + operations - 1:
		if s[index] == '(':
			openings += 1
		elif openings > 0:
			openings -= 1
		else:
			operations += 1
			s += ')'
		index += 1
	print(operations)


n = int(input())
for _ in range(n):
	k = int(input())
	l = input()
	s = []
	count = 0
	for i in l:
		if i == ')' and len(s) == 0:
			count += 1
		if i == ')' and len(s) != 0:
			s.pop(0)
		if i == '(':
			s.append('(')
	print(count)


for _ in range(int(input())):
	n = int(input())
	s = input()
	sum = count = 0
	for c in s:
		if c == '(':
			sum += 1
		if c == ')':
			sum -= 1
		if sum < 0:
			count = max(-sum, count)
	print(count)


t = int(input())
for i in range(0, t):
	p = int(input())
	s = list(input())
	l = len(s)
	sum1 = 0
	sum2 = 0
	for j in range(0, l):
		if s[j] == '(':
			sum1 += 1
		else:
			sum1 -= 1
		if sum1 < 0:
			sum2 += 1
			sum1 = 0
	print(sum2)


from sys import stdin as inp
from sys import stdout as out

def ri():
	return int(inp.readline().strip())

def rs():
	return inp.readline().strip()

def rsa():
	return inp.readline().strip().split()

def ria():
	return list(map(int, rsa()))

def pri(l, end='\n'):
	for i in l:
		out.write(str(i) + end)

def prs(l, end='\n'):
	for i in l:
		out.write(i + end)
t = ri()
mod = pow(10, 9) + 7
for _ in range(t):
	n = ri()
	s = rs()
	(o, c) = (0, 0)
	for i in s:
		if i == '(':
			o += 1
		elif i == ')':
			if o > 0:
				o -= 1
			else:
				c += 1
	if o == c:
		pri([c])
	else:
		pri([-1])


from sys import stdin, stdout
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()
import math
from collections import Counter
for _ in range(IN()):
	n = IN()
	s = S()
	ans = 0
	c = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		elif c == 0:
			ans += 1
		else:
			c -= 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ss = input()
	while '()' in ss:
		ss = ss.replace('()', '')
	countOpen = ss.count('(')
	countClosed = ss.count(')')
	if countOpen == countClosed:
		print(countOpen)


n = int(input())
for i in range(n):
	p = int(input())
	a = input()

	def bracket_match(a):
		stack = []
		pairs = 0
		for letter in a:
			if letter == '(':
				stack.append(letter)
			elif letter == ')':
				if len(stack) == 0:
					pass
				else:
					stack.pop()
					pairs += 1
		print((p - pairs * 2) // 2)
	bracket_match(a)


T = int(input())
for T in range(T):
	n = int(input())
	a = input()
	count = 0
	op = 0
	cl = 0
	for i in range(n):
		if a[i] == '(':
			op += 1
		if a[i] == ')':
			cl += 1
		if cl > op:
			count += 1
			op = 0
			cl = 0
	print(count)


a = int(input())
for i in range(a):
	r = int(input())
	s = input()
	score = 0
	count = 0
	for i in range(len(s)):
		if s[i] == ')':
			score -= 1
			if score < 0:
				score = 0
				count += 1
		else:
			score += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	st = input()
	op = 0
	li = []
	for i in range(n):
		if st[i] == '(':
			op += 1
		elif st[i] == ')':
			op -= 1
		li.append(op)
	print(-min(li))


for i in range(int(input())):
	n = int(input())
	s = input()
	a = []
	c = 0
	o = 0
	for i in range(n):
		if s[i] == ')':
			c += 1
		else:
			o += 1
		a.append(c - o)
	print(max(a))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	numOpening = 0
	numClosing = 0
	balance = 0
	min = 0
	for j in range(0, n):
		if s[j] == '(':
			numOpening += 1
		elif s[j] == ')':
			numClosing += 1
			balance = numOpening - numClosing
			if balance < min:
				min = balance
	print(-1 * min)


for _ in range(int(input())):
	input()
	s = input()
	ans = cnt = 0
	for item in s:
		if item == '(':
			cnt += 1
		else:
			cnt -= 1
			if cnt < 0:
				cnt = 0
				ans += 1
	print(ans)


t = int(input())
while t > 0:
	size = int(input())
	inp = str(input())
	reg_count = 0
	ans = 0
	for i in range(size):
		if inp[i] == '(':
			reg_count += 1
		else:
			reg_count -= 1
		if reg_count < ans:
			ans = reg_count
	print(0 - ans)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	b = 0
	m = 0
	for i in s:
		b += 1 if i == '(' else -1
		m = min(m, b)
	print(-m)


def solve():
	n = int(input())
	a = input()
	op = 0
	moves = 0
	for i in a:
		if i == '(':
			op += 1
		elif op == 0:
			moves += 1
		else:
			op -= 1
	print(moves)
t = int(input())
for test in range(t):
	solve()


def mi():
	return map(int, input().split())
for _ in range(int(input())):
	lenn = int(input())
	expr = list(input())
	t = 0
	ans = 0
	i = 0
	s = []
	for i in range(lenn):
		if expr[i] == ')' and len(s):
			if s[0] == '(':
				s.pop(0)
			else:
				s.insert(0, expr[i])
		else:
			s.insert(0, expr[i])
	print(len(s) // 2)


t = int(input())
for _t in range(t):
	n = int(input())
	s = input()
	(balanced, ans) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			balanced += 1
		else:
			balanced += -1
		if balanced < 0:
			ans += 1
			balanced = 0
	print(ans)


test = int(input())
for tes in range(test):
	len = int(input())
	arr = input()
	open = 0
	close = 0
	moves = 0
	for i in range(len):
		if arr[i] == ')':
			close = close + 1
			if close > open:
				moves = moves + 1
				close = close - 1
		else:
			open = open + 1
	print(moves)


for _ in range(int(input())):
	a = int(input())
	b = input()
	a1 = 0
	a2 = 0
	for i in range(a):
		if b[i] == '(':
			a1 += 1
		elif a1 > 0:
			a1 -= 1
		else:
			a2 += 1
	print(a1)


for T in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	st = 0
	for i in range(n):
		if s[i] == '(':
			st = st + 1
		elif st:
			st -= 1
		else:
			ans += 1
	print(ans)


t = int(input(''))
while t != 0:
	n = int(input(''))
	list1 = list(input(''))
	i = 0
	start = 0
	finish = 0
	result = 0
	while i != n - 1:
		if list1[i] == '(':
			start += 1
		else:
			finish += 1
		if finish > start:
			temp = list1[i]
			list1.pop(i)
			list1.append(temp)
			result += 1
			finish -= 1
		else:
			i += 1
	t -= 1
	print(result)


from sys import stdin
input = lambda : stdin.readline().strip()
char = [chr(i) for i in range(97, 123)]
CHAR = [chr(i) for i in range(65, 91)]
mp = lambda : list(map(int, input().split()))
INT = lambda : int(input())
rn = lambda : range(INT())
from math import ceil, sqrt, factorial, gcd
for _ in rn():
	n = INT()
	s = input()
	ans = 0
	for i in s:
		if i == '(':
			ans += 1
		elif ans > 0:
			ans -= 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	p = [0, s[0]]
	count = 0
	ans = 0
	for i in range(1, n):
		if p[-1] == '(':
			if s[i] == ')':
				p.pop()
			else:
				p.append(s[i])
		else:
			p.append(s[i])
	print(int((len(p) - 1) / 2))


n = int(input())
for x in range(n):
	y = int(input())
	s = input()
	count = 0
	mostNegative = 0
	for bracket in s:
		if bracket == '(':
			count += 1
		else:
			count -= 1
		if count < mostNegative:
			mostNegative = count
	print(abs(mostNegative))


def ans(n):
	(an, bal) = (0, 0)
	for i in n:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				an += 1
	return an
test = int(input())
res = []
while test:
	l = input()
	n = input()
	res.append(ans(n))
	test -= 1
for r in res:
	print(r, '\n')


t = int(input())
for t_i in range(t):
	input()
	s = input()
	status = 0
	min_status = 0
	for c in s:
		if c == '(':
			status += 1
		else:
			status -= 1
			min_status = min(min_status, status)
	moves = abs(min_status)
	print(moves)


from sys import stdin

def ip():
	return [int(i) for i in stdin.readline().split()]

def sp():
	return [str(i) for i in stdin.readline().split()]

def solve():
	n = int(input())
	A = list(str(input()))
	stack = []
	valid = 0
	for i in A:
		if i == ')':
			if not stack:
				continue
			else:
				stack.pop()
				valid += 1
		else:
			stack.append(i)
	return int(n // 2 - valid)
t = int(input())
for _ in range(t):
	print(solve())


t = int(input())
for fsdf in range(t):
	rub = input()
	s = input()
	balance = [0]
	ss = set()
	cnt = 0
	for i in range(len(s)):
		if s[i] == '(':
			balance.append(balance[len(balance) - 1] + 1)
		else:
			balance.append(balance[len(balance) - 1] - 1)
	for i in range(len(s)):
		for j in range(i + 1, len(s)):
			help = set()
			flag = True
			if balance[j + 1] - balance[i] == 0:
				for k in range(i, j + 1):
					if k in ss:
						flag = False
						break
					if balance[k + 1] - balance[i] < 0:
						flag = False
						break
					help.add(k)
				if flag:
					cnt += j - i + 1
					ss = ss.union(help)
	print((len(s) - cnt) // 2)


import operator as op
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from functools import reduce
from itertools import accumulate, combinations, combinations_with_replacement, groupby, permutations, product
from math import acos, asin, atan, ceil, cos, degrees, factorial, gcd, hypot, log2, pi, radians, sin, sqrt, tan
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
	return int(input())

def inlist():
	return list(map(int, input().split()))

def instr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())

def def_value():
	return 0
t = inp()
for _ in range(t):
	n = inp()
	a = input()
	stk = []
	count = 0
	for b in a:
		if b == '(':
			stk.append(b)
		elif len(stk) > 0 and b == ')':
			stk.pop()
		else:
			count += 1
	res = (count + len(stk)) // 2
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = 0
	fans = 0
	for x in s:
		if x == ')':
			st -= 1
		else:
			st += 1
		if st < 0:
			fans += 1
			st = 0
	print(fans)


for i in range(int(input())):
	n = int(input())
	s = list(input())
	cnt = 0
	k = -1
	i = 0
	while i < len(s):
		if s[i] == ')':
			i += 1
			continue
		j = i + 1
		while j < len(s):
			if s[j] == ')':
				cnt += 1
				k = j
				del s[j]
				break
			j += 1
		i += 1
	ans = n // 2 - cnt
	print(ans)


n = int(input())
for i in range(n):
	n1 = int(input())
	param = 0
	ans = 0
	seq = input()
	count = 0
	for i2 in seq:
		if i2 == '(':
			param += 1
		else:
			param -= 1
		if param < 0:
			ans += 1
			param = 0
			seq = seq[:count] + seq[count + 1:] + ')'
		count += 1
	print(ans)


def MoveBrackets():
	t = int(input())
	while t > 0:
		n = int(input())
		s = input()
		balance = count = 0
		for i in range(n):
			if s[i] == '(':
				balance += 1
			else:
				balance -= 1
				if balance < 0:
					balance = 0
					count += 1
		t -= 1
		print(count)
MoveBrackets()


t = int(input())
cases = []
for i in range(t):
	n = int(input())
	s = input()
	cases.append([n, s])

def solve(n, s):
	counter = 0
	for i in range(n - 1, -1, -1):
		if s[i] == ')':
			counter += 1
		elif counter > 0:
			counter -= 1
	return counter
for j in cases:
	print(solve(j[0], j[1]))


import sys
for _ in range(int(sys.stdin.readline().strip())):
	n = int(sys.stdin.readline().strip())
	s = sys.stdin.readline()
	while s.find('()') != -1:
		s = s.replace('()', '')
	sys.stdout.write(str(len(s) // 2) + '\n')


cases = int(input())
stk = []
for i in range(cases):
	n = int(input())
	s = input()
	stk = []
	for i in range(n):
		if s[i] == '(':
			stk.append(s[i])
		elif s[i] == ')':
			if len(stk) > 0:
				stk.pop()
	print(len(stk))


for t in range(int(input())):
	n = int(input())
	st = input()
	k = 0
	close = 0
	open = 0
	for i in range(n):
		if st[i] == ')':
			close += 1
		else:
			open += 1
		if close > open:
			k += 1
			close -= 1
	print(k)


t = int(input())
for i in range(t):
	n = int(input())
	stringa = input()
	temp_val = False
	res = 0
	left = 0
	right = 0
	for char in stringa:
		if char == '(':
			right += 1
			temp_val = True
		if char == ')' and temp_val:
			left += 1
			if left > right:
				temp_val = False
				left -= 1
		if char == ')' and (not temp_val):
			res += 1
	print(res)


for _ in range(int(input())):
	n = int(input())
	s = input()
	opened = 0
	closed = 0
	cnt = 0
	for c in s:
		if c == '(':
			opened += 1
		else:
			closed += 1
		if closed > opened:
			cnt += 1
			closed -= 1
	print(cnt)


t = int(input())
for q in range(t):
	k = 0
	ans = 0
	n = int(input())
	s = input()
	for elem in s:
		if elem == '(':
			k += 1
		elif k == 0:
			s += ')'
			ans += 1
		else:
			k -= 1
	print(ans)


for t in range(int(input())):
	n = int(input())
	arr = list(input())
	bracket = 0
	min_bracket = 0
	i = 0
	while i < n - 1:
		if arr[i] == '(':
			bracket += 1
		else:
			bracket -= 1
		i += 1
		min_bracket = min(min_bracket, bracket)
	print(abs(min_bracket))


for _ in range(int(input())):
	n = int(input())
	s = input()
	f = []
	for i in range(len(s)):
		if s[i] == '(':
			f.append(s[i])
		elif s[i] == ')':
			if f != []:
				f.pop()
	print(len(f))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	for c in s:
		if not stack:
			stack.append(c)
		elif c == stack[-1] or (c == '(' and stack[-1] == ')'):
			stack.append(c)
		else:
			stack.pop()
	print(len(stack) // 2)


for i in range(eval(input())):
	n = eval(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 2750132
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

def list_input():
	return list(map(int, input().split()))

def num_input():
	return map(int, input().split())

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	maxint = 10 ** 10
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def solve():
	n = int(input())
	s = input()
	stack = ['*']
	for i in s:
		if stack[-1] == '(' and i == ')':
			stack.pop()
		else:
			stack.append(i)
	stack.pop(0)
	if len(stack) == 0:
		print(0)
		return
	print(len(stack) // 2)
t = 1
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	k = 0
	ans = 0
	for item in s:
		if item == '(':
			k += 1
		else:
			k -= 1
		if k < 0:
			ans += 1
			k = 0
	print(ans)


def minSteps(st):
	op = 0
	cl = 0
	steps = 0
	for i in st:
		if i == '(':
			op += 1
		else:
			cl += 1
		if op - cl < 0:
			steps = max(cl - op, steps)
	return steps
T = int(input())
for i in range(T):
	n = int(input())
	st = input()
	print(minSteps(st))


for _ in range(int(input())):
	n = int(input())
	s = input()
	res = 0
	m = float('inf')
	for i in s:
		if i == '(':
			res += 1
		elif i == ')':
			res -= 1
		m = min(m, res)
	print(-m)


for i in range(int(input())):
	n = int(input())
	k = list(input())
	s = 0
	x = 0
	for j in range(n):
		if k[j] == ')':
			x = x + 1
			s = max(s, x)
		else:
			x = x - 1
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	a = str(input())
	word = []
	for i in range(n):
		word.append(a[i])
	i = 0
	openb = 0
	closeb = 0
	ans = 0
	while i < n:
		if word[i] == '(':
			openb += 1
		else:
			closeb += 1
		if openb == closeb:
			openb = 0
			closeb = 0
		if word[i] == '(' and closeb > openb:
			word.pop(i)
			word.insert(0, '(')
			ans += 1
			i = -1
			openb = 0
			closeb = 0
		elif word[i] == ')' and closeb > openb:
			word.pop(i)
			word.append(')')
			ans += 1
			i = -1
			openb = 0
			closeb = 0
		i += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = input()
	s = []
	c = 0
	for i in a:
		if i == '(':
			s.append(i)
		elif len(s) == 0:
			c += 1
		else:
			s.pop()
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	if s == '':
		print(0)
		continue
	print(len(s) // 2)


t = int(input())
for _ in range(0, t):
	n = int(input())
	st = str(input())
	ans = 0
	stack = []
	for i in range(0, len(st)):
		if st[i] == '(':
			stack.append(st[i])
		elif len(stack) > 0:
			stack.pop()
		else:
			ans += 1
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	c = 0
	moves = 0
	for i in s:
		if i == '(':
			c += 1
		if c == 0 and i == ')':
			moves += 1
		if c != 0 and i == ')':
			c -= 1
	print(moves)
	t -= 1


import sys
readline = sys.stdin.readline
t = int(readline())
for _ in range(t):
	n = int(readline())
	S = readline().rstrip()
	depth_max = 0
	depth = 0
	for s in S:
		if s == '(':
			depth += 1
		else:
			depth -= 1
		if depth < depth_max:
			depth_max = depth
	print(-depth_max)


from __future__ import division, print_function
from sys import stdin, stdout
import bisect
import math
import heapq
i_m = 9223372036854775807

def inin():
	return int(input())

def stin():
	return input()

def spin():
	return map(int, stin().split())

def lin():
	return list(map(int, stin().split()))

def matrix(n):
	return [list(map(int, input().split())) for i in range(n)]

def count2Dmatrix(i, list):
	return sum((c.count(i) for c in list))

def modinv(n, p):
	return pow(n, p - 2, p)

def GCD(x, y):
	x = abs(x)
	y = abs(y)
	if min(x, y) == 0:
		return max(x, y)
	while y:
		(x, y) = (y, x % y)
	return x

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l
prime = []

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j
for _ in range(inin()):
	n = inin()
	s = list(stin())
	c = 0
	temp = 0
	i = 0
	while i + 1 < len(s):
		if not '()' in ''.join(s):
			break
		if s[i] == '(' and s[i + 1] == ')':
			del s[i]
			del s[i]
			i = 0
		else:
			i += 1
	print(len(s) // 2)


output = []
for _ in range(int(input())):
	num = int(input())
	paran = input()
	for x in range(num):
		paran = paran.replace('()', '')
	output.append(int(len(paran) / 2))
for x in output:
	print(x)


def countSetBits(n):
	count = 0
	while n:
		count += n & 1
		n >>= 1
	return count

def bubble_sort(c):
	n = len(c)
	for i in range(n):
		already_sorted = True
		for j in range(n - i - 1):
			if c[j][0] < c[j + 1][0]:
				(c[j][0], c[j + 1][0]) = (c[j + 1][0], c[j][0])
				already_sorted = False
			if c[j][0] == c[j + 1][0]:
				if c[j][1] > c[j + 1][1]:
					(c[j][1], c[j + 1][1]) = (c[j + 1][1], c[j][1])
		if already_sorted:
			break
	return c

def perform_bubble_sort(blist):
	(cmpcount, swapcount) = (0, 0)
	blist = list(map(int, input().split()))
	for j in range(len(blist)):
		for i in range(1, len(blist) - j):
			cmpcount += 1
			if blist[i - 1] > blist[i]:
				swapcount += 1
				(blist[i - 1], blist[i]) = (blist[i], blist[i - 1])
	print(swapcount)

def fun(l, c, d):
	if c == n:
		return d
	if c % 2 == 0:
		d = max(fun(l[:-1], c + 1, d + l[-1]), fun(l[1:], c + 1, d + l[0]))
	else:
		d = min(fun(l[1:], c + 1, d - l[0]), fun(l[:-1], c + 1, d - l[-1]))
	return d
t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	a = 0
	for i in range(n):
		if s[i] == '(':
			a += 1
		if s[i] == ')':
			if a > 0:
				a -= 1
	print(a)


def solve(s, n):
	o = 0
	c = 0
	count = 0
	for i in s:
		if i == '(':
			o += 1
		else:
			c += 1
			if c > o:
				count += 1
				c -= 1
	return count
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	print(solve(s, n))


rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))
INF = float('inf')

def solve(N, S):
	invalid = 0
	bal = 0
	for b in S:
		if b == ')':
			bal -= 1
			if bal < 0:
				bal = 0
				invalid += 1
		else:
			bal += 1
	return invalid
t = rri()
for _ in range(t):
	n = rri()
	s = rr()
	print(solve(n, s))


t = int(input())
for _ in range(t):
	n = int(input())
	str1 = input()
	l = []
	for i in range(n):
		if str1[i] == '(':
			l.append('(')
		else:
			temp = len(l)
			if temp == 0:
				l.append(')')
			elif l[temp - 1] == '(':
				l.pop(temp - 1)
			else:
				l.append(')')
	print(len(l) // 2)


for t in range(int(input())):
	n = int(input())
	s = input()
	max_dif = 0
	open = 0
	close = 0
	for i in range(n):
		if s[i] == '(':
			open += 1
		else:
			close += 1
		if close - open > max_dif:
			max_dif = close - open
	print(max_dif)


t = int(input())
for i in range(t):
	n = int(input())
	ar = [str(i) for i in input()]
	op = 0
	en = 0
	sw = 0
	for x in range(n):
		if ar[x] == '(':
			op += 1
		else:
			en += 1
		if en > op:
			sw += 1
			en -= 1
		else:
			pass
	print(sw)


test_case = int(input())
for i in range(test_case):
	n = int(input())
	arr = list(input())
	counter = 0
	flag = 0
	l = []
	for i in arr:
		if i in arr:
			if i == '(':
				l.append('(')
				continue
			if i == ')':
				if len(l) > 0:
					l.pop()
	print(len(l))


for i in range(int(input())):
	stack = []
	n = int(input())
	s = input()
	for i in s:
		if i == ')':
			if '(' in stack:
				stack.pop()
		else:
			stack.append(i)
	print(len(stack))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	s = s[::-1]
	o = 0
	c = 0
	mo = 0
	for i in s:
		if i == '(':
			o += 1
		if i == ')':
			c += 1
		if o > c:
			mo += 1
			o -= 1
		elif o == c:
			o = 0
			c = 0
	print(mo)


t = int(input())
for i in range(0, t):
	n = int(input())
	msg0 = input()
	lst = []
	for k in range(0, len(msg0)):
		if msg0[k] == '(':
			lst.append(1)
		else:
			lst.append(-1)
	count = 0
	j = 0
	while j <= len(lst) - 1:
		sum1 = 0
		for k in range(0, j + 1):
			sum1 += lst[k]
		if sum1 < 0:
			lst.remove(lst[j])
			lst.append(-1)
			count += 1
			j -= 1
		j += 1
	print(count)


test_case = int(input())
for _ in range(test_case):
	a = input()
	b = input()
	c = []
	for i in b:
		if not len(c) or c[-1] == i or (c[-1] == ')' and i == '('):
			c.append(i)
		else:
			c.pop(-1)
	print(len(c) // 2)


tot = int(input().strip())
while tot > 0:
	n = int(input().strip())
	s = list(input().strip())
	stk = 0
	mv = [False] * n
	ans = 0
	for i in range(0, n):
		if s[i] == '(':
			if mv[i] == False:
				stk += 1
		elif stk > 0:
			stk -= 1
		else:
			for j in range(n - 1, i, -1):
				if mv[j] == False:
					mv[j] = True
					ans += 1
					break
	print(ans)
	tot -= 1


import bisect
import sys
import math
input = sys.stdin.readline
import functools
from collections import defaultdict

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solve(case):
	n = inp()
	s = input().rstrip('\n')
	op_unused = 0
	res = 0
	for c in s:
		if c == '(':
			op_unused += 1
		elif op_unused > 0:
			op_unused -= 1
		else:
			res += 1
			op_unused = 0
	return res
if len(sys.argv) > 1 and sys.argv[1].startswith('input'):
	f = open('./' + sys.argv[1], 'r')
	input = f.readline
T = inp()
for i in range(T):
	res = solve(i + 1)
	print(str(res))


from sys import stdin, stdout
from sys import maxsize

def solve():
	pass
test = 1
test = int(input())
for t in range(0, test):
	n = int(input())
	s = list(input())
	(no, nc, moves) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			no += 1
		else:
			nc += 1
		if nc > no:
			nc -= 1
			moves += 1
	print(moves)
	ans = solve()


def turns(n, s):
	diff = 0
	counter = 0
	for c in s:
		if c == ')' and diff <= 0:
			counter += 1
		elif c == ')':
			diff -= 1
		elif c == '(':
			diff += 1
	return counter
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(turns(n, s))


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	s = []
	x = 0
	for i in a:
		if i == ')' and s == []:
			x += 1
		elif i == ')' and s[-1] == '(':
			del s[-1]
		else:
			s.append(i)
	print((len(s) + x) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(match, o) = (0, 0)
	for c in s:
		if c == ')':
			if o:
				match += 1
				o -= 1
		else:
			o += 1
	print(n // 2 - match)


def solve():
	n = int(input())
	s = input()
	d = 0
	m = 0
	for i in range(n):
		if s[i] == '(':
			d += 1
		else:
			d -= 1
			if d < m:
				m = d
	print(-m)
for _ in range(int(input())):
	solve()


for i in range(int(input())):
	n = int(input())
	s = input()
	(l, c) = (0, 0)
	d = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		elif s[i] == ')':
			c -= 1
		if c < 0:
			c = 0
			d += 1
	print(d)


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, s):
	i = 0
	while i < len(s) - 1:
		if s[i] == '(' and s[i + 1] == ')':
			s = s[:i] + s[i + 2:]
			i -= 1
			if i < 0:
				i = 0
		else:
			i += 1
	return len(s) // 2

def main():
	for _ in range(ri()):
		n = ri()
		s = rs()
		wi(solve(n, s))
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	op = 0
	cl = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			op += 1
		else:
			cl += 1
			if cl > op:
				ans = max(ans, cl - op)
	print(ans)


n = int(input())
for i in range(n):
	a = int(input())
	b = input()
	count = 0
	result = []
	for j in b:
		if j == ')':
			if len(result) > 0 and result[-1] == '(':
				result.pop()
			else:
				count += 1
		else:
			result.append(j)
	print(count)


t = int(input())
for isc in range(t):
	n = int(input())
	s = input()
	dif = 0
	maxdif = 0
	for c in s:
		if c == '(':
			dif -= 1
		else:
			dif += 1
			if dif > maxdif:
				maxdif = dif
	print(maxdif)


testCases = int(input())
while testCases:
	testCases -= 1
	y = int(input())
	word = input()
	o = 0
	c = 0
	for i in word:
		if i == '(':
			o += 1
		elif o > 0:
			o -= 1
		else:
			c += 1
	print(o)


for _ in range(int(input())):
	n = int(input())
	s = input()
	x = 0
	for i in range(n):
		if s.count('()') > 0:
			s = s.replace('()', '')
		else:
			break
	for i in range(n):
		if s.count(')(') > 0:
			x += s.count(')(')
			s = s.replace(')(', '')
		else:
			break
	print(x)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	left = 0
	ans = 0
	for x in s:
		if x == '(':
			left += 1
		elif left > 0:
			left -= 1
		else:
			ans += 1
	print(ans)


def read_int():
	n = int(input())
	return n

def read_ints():
	ints = [int(x) for x in input().split(' ')]
	return ints

def solve(n, s):
	dp = [[0 for _ in range(n)] for _ in range(2)]
	for i in range(n):
		dp[0][i] = 1 if s[i] == '(' else -1
		dp[1][i] = dp[1][i - 1] + dp[0][i] if i != 0 else dp[0][i]
	sol = min(dp[1]) * -1
	if sol < 0:
		return 0
	return sol
t = read_int()
for case in range(t):
	n = read_int()
	s = input()
	sol = solve(n, s)
	print(sol)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c = 0
	min_c = 0
	for j in range(n):
		if s[j] == ')':
			c -= 1
		else:
			c += 1
		if c < min_c:
			min_c = c
	print(abs(min_c))


t = int(input())
for test in range(t):
	n = int(input())
	s = input()
	op = 0
	mn = float('inf')
	for i in s:
		if i == ')':
			op -= 1
		else:
			op += 1
		mn = min(mn, op)
	print(-mn)


from sys import stdin, stdout, setrecursionlimit
from math import ceil
for i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	while True:
		cou = []
		ok1 = ans
		for i in range(n):
			if s[i] == '(':
				cou.append(s[i])
			elif len(cou) == 0:
				ans += 1
				s = s[:i] + s[i + 1:] + s[i]
				break
			else:
				cou.pop()
		ok2 = ans
		if ok1 == ok2:
			break
	print(ans)


tests = int(input())
for test in range(tests):
	n = int(input())
	s = input()
	(b, mb) = (0, 0)
	for c in s:
		b += 1 if c == '(' else -1
		mb = min(mb, b)
	print(-mb)


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	l = []
	ele = s[0]
	v = 0
	for i in range(n):
		if ele == s[i]:
			v += 1
		else:
			l.append(v)
			v = 1
			ele = s[i]
	l.append(v)
	ind = 0
	if s[0] == '(':
		ind = 1
	for i in range(ind, len(l), 2):
		l[i] *= -1
	ln = len(l)
	(mx, pos, neg) = (0, 0, 0)
	for i in range(ln):
		if l[i] > 0:
			pos += l[i]
		else:
			neg += l[i]
		if neg * -1 > pos:
			mx = max(mx, abs(neg + pos))
	print(mx)


for i in range(int(input())):
	n = int(input())
	count = 0
	s1 = input()
	for j in range(n):
		if s1[j] == '(':
			count += 1
		elif s1[j] == ')' and count > 0:
			count -= 1
	print(count)


import re
n = int(input())
for _ in range(n):
	_ = input()
	s = str(input())
	while s.count('()') > 0:
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	p = str(input())
	l = []
	for i in range(n):
		l.append(p[i])
	op = 0
	cp = 0
	i = 0
	m = 0
	while i < n:
		if l[i] == '(':
			op += 1
		else:
			cp += 1
		if op == cp:
			op = 0
			cp = 0
		if l[i] == '(' and cp > op:
			l.pop(i)
			l.insert(0, '(')
			m += 1
			i = -1
			op = 0
			cp = 0
		elif l[i] == ')' and cp > op:
			l.pop(i)
			l.append(')')
			m += 1
			i = -1
			cp = 0
			op = 0
		i += 1
	print(m)


def main():
	(n,) = map(int, input().split(' '))
	s = input()
	d = [0]
	curr = 0
	for i in range(n):
		if s[i] == '(':
			d.append(curr)
			curr += 1
		else:
			curr -= 1
	d.sort()
	print(-d[0])
for _ in range(int(input())):
	main()


import math
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()[:-1]
	bal = 0
	ans = 0
	st = ['$']
	for i in s:
		if i == '(':
			st.append('(')
		elif i == ')' and st[-1] == '(':
			st.pop(-1)
		else:
			st.append(')')
	xctr = 0
	for i in st:
		if i == ')':
			xctr += 1
	print(xctr)


def minParentheses(p):
	bal = 0
	ans = 0
	for i in range(0, len(p)):
		if p[i] == '(':
			bal += 1
		else:
			bal += -1
		if bal == -1:
			ans += 1
			bal += 1
	return bal + ans
try:
	t = int(input())
	while t:
		n = int(input())
		s = input()
		x = minParentheses(s)
		print(x // 2)
except:
	pass


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = input()
	st = []
	for ch in s:
		if not st:
			st += [ch]
		elif ch == ')' and st[-1] == '(':
			st.pop()
		else:
			st += [ch]
	print(len(st) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	z = 0
	z2 = 0
	for i in range(n):
		if s[i] == '(':
			z += 1
		else:
			z -= 1
		if z < 0:
			z2 += 1
			z = 0
	print(z2)


def sol():
	x = int(input())
	s = list(input())
	v = s.copy()
	a = 0
	b = 0
	for n in range(x):
		if s[n] == ')':
			u = 0
			for k in range(n):
				if s[k] == '(':
					s[n] = 'a'
					s[k] = 'a'
					u = 1
					break
			if not u:
				a += 1
	for n in range(x):
		if s[n] == '(':
			u = 0
			for k in range(n + 1, x):
				if s[k] == ')':
					u = 1
					s[k] = 'a'
					s[n] = 'a'
					break
			if not u:
				b += 1
	print(max(a, b))
for n in range(int(input())):
	sol()


t = int(input())
while t:
	t -= 1
	n = int(input())
	st = input()
	string = []
	for i in range(n):
		if st[i] == '(':
			string.append('(')
		elif st[i] == ')':
			if len(string) != 0:
				string.pop()
	print(len(string))


t = int(input())
for _ in range(t):
	n = int(input())
	(ct, ans) = (0, 0)
	for c in input():
		if c == '(':
			ct += 1
		else:
			ct -= 1
		if ct == -1:
			ans += 1
			ct = 0
	print(ans)


n = int(input())
for i in range(n):
	z = 0
	x = 0
	s = int(input())
	t = input()
	for j in t:
		if j == '(':
			x += 1
		elif j == ')':
			if x > 0:
				x -= 1
				z += 1
	print((s - z * 2) // 2)


from math import log

def solve():
	n = int(input())
	s = input()
	op = 0
	cl = 0
	ch = 0
	for (i, c) in enumerate(s):
		if c == '(':
			op += 1
		if c == ')':
			cl += 1
		if cl - ch > op:
			ch += 1
	print(ch)
t = int(input())
for _ in range(t):
	solve()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	s = input()
	mi = 0
	c = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		mi = min(mi, c)
	print(abs(mi))


t = int(input())
while t != 0:
	t -= 1
	x = int(input())
	bt = input()
	st = []
	cnt = 0
	for c in bt:
		if c == '(':
			st.append(c)
		elif len(st) > 0 and st[-1] == '(':
			st.pop()
		else:
			cnt += 1
	print(cnt)


import sys, math
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input().strip()

def listStr():
	return list(input().strip())
import collections as col
import math

def solve():
	N = getInt()
	S = listStr()
	max_neg = 0
	curr_sum = 0
	for s in S:
		if s == '(':
			curr_sum += 1
		else:
			curr_sum -= 1
		max_neg = min(max_neg, curr_sum)
	return -max_neg
for _ in range(getInt()):
	print(solve())


import time
from collections import deque

def inpt():
	return int(input())

def inpl():
	return list(map(int, input().split()))

def inpm():
	return map(int, input().split())

def solve():
	n = int(input())
	s = input()
	l = []
	r = []
	ans = 0
	for i in s:
		if i == '(':
			l.append('(')
		elif len(l) >= 1 and i == ')':
			l.pop()
		else:
			r.append(')')
	ans = len(r)
	l = []
	r = []
	for i in s[::-1]:
		if i == ')':
			l.append(')')
		elif len(l) >= 1 and i == '(':
			l.pop()
		else:
			r.append('(')
	ans = min(ans, len(r))
	print(ans)

def main():
	m = 10 ** 9 + 7
	t = int(input())
	while t:
		t -= 1
		solve()
main()


from sys import stdin
input = stdin.readline
INF = 10 ** 9 + 7
MAX = 10 ** 7 + 7
MOD = 10 ** 9 + 7
for Ti in range(int(input().strip())):
	n = int(input().strip())
	s = input().strip()
	cnt = 0
	ans = 0
	for si in s:
		if si == '(':
			cnt += 1
		elif cnt > 0:
			cnt -= 1
		else:
			ans += 1
	print(ans)


b = int(input())
for p in range(0, b):
	l = int(input())
	a = str(input())
	for j in range(0, l // 2):
		for i in a:
			a = a.replace('()', '')
	print(len(a) // 2)


a = int(input())
for i in range(0, a):
	b = int(input())
	s = input()
	arr = []
	for i in s:
		if i == '(':
			arr.append(1)
		else:
			arr.append(-1)
	oc = 0
	count = 0
	for i in range(0, len(arr)):
		if arr[i] == 1:
			oc = oc + 1
		if arr[i] == -1:
			if oc - 1 < 0:
				count = count + 1
			else:
				oc = oc - 1
	print(count)


import sys
test_cases = int(input())
while test_cases != 0:
	test_cases -= 1
	n = int(input())
	s = input()
	wrong_right_side_bracket_count = 0
	left_side_bracket_remain = 0
	for ch in s:
		left_or_right = ch == '('
		if left_or_right:
			left_side_bracket_remain += 1
		elif left_side_bracket_remain > 0:
			left_side_bracket_remain -= 1
		else:
			wrong_right_side_bracket_count += 1
	print(wrong_right_side_bracket_count)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	nc = 0
	no = 0
	f = 0
	for x in s:
		if x == '(':
			no += 1
		elif x == ')' and no <= nc:
			f += 1
		else:
			nc += 1
	print(f)


t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	s = input()
	arr = []
	c = 0
	for i in range(len(s)):
		if s[i] == '(':
			arr.append(s[i])
		elif s[i] == ')':
			if len(arr) == 0 or arr[-1] != '(':
				c += 1
			else:
				arr.pop()
	print(c)


t = int(input())
while t:
	k = int(input())
	n = input()
	xopen = 0
	yclose = 0
	count = 0
	flag = 0
	prefix = [0] * k
	for i in range(len(n)):
		if i == 0:
			if n[i] == '(':
				prefix[i] = -1
			else:
				prefix[i] = 1
		elif n[i] == '(':
			prefix[i] = prefix[i - 1] - 1
		else:
			prefix[i] = prefix[i - 1] + 1
	print(max(prefix))
	t = t - 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	stack = []
	for i in s:
		if stack:
			if stack[-1] != i:
				stack.pop()
				continue
		if i == '(':
			stack.append(i)
	print(len(stack))


for _ in range(int(input())):
	N = int(input())
	S = input()
	A = B = C = 0
	for i in S:
		if i == '(':
			A += 1
		else:
			B += 1
		if B > A:
			C += 1
			B -= 1
	print(C)


for _ in range(int(input())):
	n = int(input())
	st = input()
	stk = []
	due = 0
	for i in st:
		if not (not stk and i == ')'):
			if i == '(':
				stk.append(1)
			elif i == ')':
				t = stk.pop(-1)
	print(len(stk))


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			c = 0
			ans += 1
	print(ans)


for i in range(int(input())):
	n = int(input())
	st = list(input())
	ar = 0
	for i in st:
		if i == '(':
			ar += 1
		if i == ')':
			if ar != 0:
				ar -= 1
	print(ar)


import math
T = int(input())
for _ in range(0, T):
	a = [')', '(', ')', '(', ')', '(']
	n = int(input())
	s = input()
	m = []
	for letter in s:
		m.append(letter)
	while '()' in s:
		for i in range(0, len(m) - 1):
			if m[i] == '(':
				if m[i + 1] == ')':
					del m[i]
					del m[i]
					break
		s = ''.join(m)
	print(len(s) // 2)


def solve():
	n = int(input())
	s = input()
	bal = 0
	minbal = 0
	for (i, e) in enumerate(s):
		if e == ')':
			bal -= 1
		else:
			bal += 1
		minbal = min(bal, minbal)
	print(-minbal)
[solve() for i in range(int(input()))]


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	errcount = 0
	for c in s:
		if c == '(':
			stack.append(c)
		else:
			try:
				stack.pop()
			except:
				errcount += 1
	print(errcount | len(stack))


for _ in range(int(input())):
	y = int(input())
	x = input()
	temp = counter = 0
	for i in range(y):
		if x[i] == ')':
			temp -= 1
		elif x[i] == '(':
			if temp < 0:
				counter += abs(temp)
				temp = 1
			else:
				temp += 1
	print(counter)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	f = 1
	while f:
		f = 0
		for i in range(len(s) - 1):
			if s[i] == '(' and s[i + 1] == ')':
				f = 1
		if f:
			s = s.replace('()', '')
	print(len(s) // 2)


for _ in range(int(input())):
	n = int(input())
	maxx = 0
	k = 0
	s = input()
	for i in s:
		if i == '(':
			k -= 1
		else:
			k += 1
			if k > maxx:
				maxx = k
	print(maxx)


tcs = int(input())
for tc in range(tcs):
	n = int(input())
	br = input()
	l_st = 0
	r_st = 0
	for b in br:
		if b == '(':
			r_st += 1
		elif b == ')' and r_st != 0:
			r_st -= 1
		elif b == ')':
			l_st += 1
	print(l_st)


for _ in range(int(input())):
	n = int(input())
	l = list(input())
	stack = []
	size = 0
	for i in range(n):
		if l[i] == '(':
			stack.append(l[i])
			size += 1
		elif size != 0:
			stack.pop()
			size -= 1
	print(size)


t = int(input())
for ex in range(t):
	n = int(input())
	s = str(input())
	sl = list(s)
	o_num = int(0)
	ans1 = int(0)
	for i in range(n):
		if sl[i] == '(':
			o_num += 1
		elif o_num > 0:
			o_num -= 1
		else:
			ans1 += 1
	print(ans1)


n = int(input())
for _ in range(n):
	ln = int(input())
	ll = input()
	l = []
	for i in ll:
		if i == '(':
			l.append(i)
		elif len(l) == 0:
			l.append(i)
		elif l[-1] == '(':
			l.pop()
		else:
			l.append(i)
	print(len(l) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	c = 0
	z = 0
	for i in s:
		if i == '(':
			st.append(i)
			c += 1
		elif i == ')':
			if len(st) > 0 and st.pop(-1) == '(':
				z += 1
	t = n - 2 * min(c, z)
	print(t // 2)


tests = int(input())
for i in range(tests):
	size = int(input())
	sequence = input()
	pending = 0
	open_brace = 0
	for i in range(size):
		if sequence[i] == '(':
			open_brace += 1
		elif open_brace != 0:
			open_brace -= 1
		else:
			pending += 1
	print(pending)


k = int(input())
for i in range(k):
	leng = int(input())
	arr = input()
	ans = 0
	temp = 0
	for j in range(leng):
		if arr[j] == '(':
			temp = temp - 1
		else:
			temp = temp + 1
		ans = max(ans, temp)
	print(ans)


t = int(input())
for p in range(t):
	ans = 0
	n = int(input())
	s = input()
	stk = []
	for i in s:
		if i == '(':
			stk.append('(')
		if i == ')':
			if not stk:
				ans += 1
			else:
				stk.pop()
	print(ans)


cases = int(input())
for i in range(cases):
	length = int(input())
	string = input()
	count = 0
	ans = 0
	for j in range(length):
		if string[j] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			k = string.rfind('(')
			ans += 1
			count = 0
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	sumi = 0
	for i in range(n):
		if s[i] == ')':
			sumi += 1
		else:
			sumi -= 1
		ans = max(ans, sumi)
	print(ans)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	arr = []
	cnt = 0
	for i in s:
		if i == '(':
			if len(arr) != 0:
				arr.pop()
			stack.append(i)
		elif len(stack) == 0:
			cnt += 1
			arr.append(i)
		else:
			stack.pop()
	print(cnt)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	while '()' in a:
		pos = a.find('()')
		a = a[:pos] + a[pos + 2:]
	count = len(a) // 2
	print(count)


import collections
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	q = collections.deque()
	count = 0
	for x in s:
		if x == '(':
			q.append(x)
		elif x == ')' and q:
			q.pop()
		else:
			count += 1
	print(count)


t = int(input())
for qw in range(t):
	n = int(input())
	s = input()
	ans = 0
	minans = 0
	for i in s:
		if i == '(':
			ans += 1
		else:
			ans -= 1
		minans = min(ans, minans)
	print(abs(minans))


def is_pw(x):
	d = 1
	while d < x:
		d *= 3
	return d == x
for _ in range(int(input())):
	n = int(input())
	s = input()
	pref = 0
	k = 0
	for i in s:
		if i == '(':
			pref += 1
		else:
			pref -= 1
		if pref < 0:
			k += 1
			pref = 0
	print(k)


n1 = int(input())
for x in range(n1):
	a = int(input())
	b = input()
	for y in range(int(a / 2)):
		b = b.replace('()', '')
	print(int(len(b) / 2))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	c1 = 0
	c2 = 0
	c = 0
	for i in s:
		if i == '(':
			c1 += 1
		elif i == ')':
			c2 += 1
		if c2 > c1:
			c += 1
			c2 -= 1
	print(c)


import sys
t = 1
t = int(input())
for i in range(t):
	n = int(input())
	x = list(input())
	op = 0
	xx = 0
	for j in x:
		if j == ')':
			xx += 1
		else:
			xx -= 1
		op = max(op, xx)
	print(op)


def isPrime(n):
	if n % 2 == 0:
		return n == 2
	d = 3
	while d * d <= n and n % d != 0:
		d += 2
	return d * d > n

def task_C():
	t = int(input())
	for _ in range(t):
		n = int(input())
		string = input()
		count_beg = 0
		count_end = 0
		for char in string:
			if char == ')':
				if count_beg > 0:
					count_beg -= 1
				else:
					count_end += 1
			else:
				count_beg += 1
		print(count_end)

def main():
	task_C()
main()


for t in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	openBr = 0
	closeBr = 0
	i = 0
	fix = 0
	while i < n:
		if s[i] == '(':
			openBr += 1
		else:
			closeBr += 1
		i += 1
		if closeBr > openBr:
			i -= 1
			cnt += 1
			s = s[:i] + s[i + 1:] + ')'
			openBr = 0
			closeBr = 0
			i = fix
		if closeBr == openBr:
			fix = i
	print(cnt)


for i in ' ' * int(input()):
	a = int(input())
	b = input()
	while '()' in b:
		b = b.replace('()', '')
	print(len(b) // 2)


from math import *
t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	open = 0
	ans = 0
	for i in range(n):
		if a[i] == '(':
			open += 1
		else:
			open = open - 1
			if open < 0:
				ans += 1
				open = 0
	print(ans)


for t in range(int(input())):
	n = int(input())
	st = input()
	l = []
	c = 0
	for i in range(n):
		if st[i] == '(':
			l.append(st[i])
		elif len(l) != 0:
			l.pop()
		else:
			c += 1
	print(c)


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['YES', 'NO']
test_case = ii()
while test_case:
	test_case -= 1
	n = ii()
	a = lsi()
	c = p = 0
	for i in a:
		if i == '(':
			p += 1
		else:
			p -= 1
			if p < 0:
				p = 0
				c += 1
	print(c)


try:
	for i in range(int(input())):
		size = int(input())
		string = input()
		j = 0
		count = 0
		balance = 0
		while j < len(string):
			if string[j] == '(':
				balance += 1
			else:
				balance -= 1
			if balance < 0:
				string = string + ')'
				count += 1
				balance += 1
			j += 1
		print(count)
except:
	pass


t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	ans = 0
	for num in range(n):
		if s[num] == ')':
			if ans > 0:
				ans -= 1
		if s[num] == '(':
			ans += 1
	print(abs(ans))


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	lst = list()
	lst.append(s[0])
	j = 0
	for i in range(1, n):
		if j == -1:
			lst.append(s[i])
			j += 1
		elif s[i] == ')' and lst[j] == '(':
			lst.pop()
			j -= 1
		else:
			lst.append(s[i])
			j += 1
	print((j + 1) // 2)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	pilha = []
	total = 0
	for c in s:
		if c == '(':
			pilha.append(c)
		elif len(pilha) > 0:
			pilha.pop()
		else:
			total += 1
	print(total)


def solve(s):
	r = 0
	m = 0
	for i in range(len(s)):
		if s[i] == ')':
			r += 1
			m = max(m, r)
		else:
			r -= 1
	return m
test = int(input())
for i in range(test):
	m = input()
	arr = input()
	print(solve(arr))


test = int(input())
for i in range(test):
	no = int(input())
	count = 0
	s = input()
	ans = 0
	for j in range(no):
		if s[j] == '(':
			count += 1
		else:
			count -= 1
		if count == -1:
			count = 0
			ans += 1
	print(ans)


t = int(input())
while t:
	n = int(input())
	s = str(input())
	ans = 0
	for i in range(n):
		if s[i] == '(':
			ans += 1
		elif ans >= 1:
			ans -= 1
	print(ans)
	t -= 1


t = int(input())
for test in range(t):
	n = int(input())
	s = input()
	u = [0]
	for i in s:
		if i == ')':
			u.append(u[-1] + 1)
		else:
			u.append(u[-1] - 1)
	print(max(u))


t = int(input())

def fun(n, a):
	ans = 0
	count = 0
	i = 0
	while i < n:
		if a[i] == '(':
			count += 1
		else:
			count -= 1
		i += 1
		if count < 0:
			ans += 1
			count += 1
	print(int(ans))
while t:
	t -= 1
	n = int(input())
	a = input()
	fun(n, a)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack = []
	cnt = 0
	if s[0] == '(':
		stack.append(s[0])
		i = 1
	else:
		s += s[0]
		cnt += 1
		s = s[1:]
		i = 0
	while i < len(s):
		if s[i] == '(':
			stack.append('(')
			i += 1
		elif len(stack) == 0:
			s += ')'
			s = s[1:]
			cnt += 1
		else:
			stack.pop()
			i += 1
	print(cnt)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	n = inputnum()
	s = inputstring()
	opened = 0
	closed = 0
	ans = 0
	for c in s:
		if c == '(':
			opened += 1
		else:
			closed += 1
		if closed > opened:
			closed -= 1
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = input()
	s = [0] * n
	flag = 0
	for t in range(n):
		if l[t] == '(':
			flag += 1
		else:
			flag -= 1
		s[t] = flag
	sum = 0
	i = 0
	while i < n:
		if s[i] < 0:
			sum += 1
			del s[i]
			for j in range(i, n - 1):
				s[j] += 1
			s.append(0)
			i -= 1
		i += 1
	print(sum)


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = stdin.readline().rstrip()
	count = 0
	countOp = 0
	for i in s:
		if i == '(':
			countOp += 1
		elif countOp > 0:
			countOp -= 1
		else:
			count += 1
	print(count)


L = int(input())

def bracket(n, m):
	count = 0
	while len(m) > 0:
		for i in range(len(m)):
			if m[i] == '(':
				for j in range(i, len(m)):
					if m[j] == ')':
						m = m[:i] + m[i + 1:j] + m[j + 1:]
						break
					elif ')' not in m[i:]:
						m = m[-1] + m[:-1]
						count += 1
						break
				break
	return count
for i in range(L):
	n = int(input())
	m = str(input())
	ans = bracket(n, m)
	print(ans)


for _ in range(int(input())):
	input()
	base = []
	for i in input():
		if len(base) == 0:
			base.append(i)
		elif i == ')' and base[-1] == '(':
			del base[-1]
		else:
			base.append(i)
	print(len(base) // 2)


t = int(input())
for i in range(0, t):
	length = int(input())
	max = input()
	steps = 0
	pairs = 0
	h = 0
	max1 = []
	max2 = []
	spam1 = 0
	eggs1 = 1
	spam = 0
	eggs = 1
	for j in range(0, len(max)):
		max1.append(max[j])
	while len(max1) != 0 and len(max1) >= len(max2) and (len(max1) != length - pairs * 2) or len(max1) >= 2:
		if len(max1) == len(max2):
			break
		if max1[0] == ')':
			max2.append(max1[0])
			max1.remove(max1[0])
		elif len(max1) >= 2:
			if max1[spam] == '(' and max1[eggs] == ')':
				pairs += 1
				max1.remove(max1[eggs])
				max1.remove(max1[spam])
				spam = 0
				eggs = 1
			elif max1[spam] == '(' and max1[eggs] == '(':
				spam += 1
				eggs += 1
			else:
				max2.append(max1[eggs])
				max1.remove(max1[eggs])
				max2.append(max1[spam])
				max1.remove(max1[spam])
		else:
			break
	len1 = len(max1) + len(max2)
	steps = int(len1 / 2)
	print(steps)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = list(s)
	r = list(s)
	for i in range(n - 1):
		if r[i] == '(':
			for j in range(i + 1, n):
				if r[j] == ')':
					r[j] = '-1'
					break
	for i in range(n - 1, -1, -1):
		if l[i] == ')':
			for j in range(i - 1, -1, -1):
				if l[j] == '(':
					l[j] = '-1'
					break
	ar = r.count('(')
	br = r.count('-1')
	al = l.count(')')
	bl = l.count('-1')
	ans = (ar - br + (al - bl)) // 2
	print(ans)


t = int(input())
ans = [0] * t
for j in range(t):
	n = int(input())
	s = input()
	opn = badopn = cls = badcls = 0
	for i in s:
		if i == ')':
			cls += 1
			if opn > 0:
				opn -= 1
			else:
				badcls += 1
		else:
			opn += 1
	ans[j] = badcls
for i in ans:
	print(i)


import sys, math
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	string = [char for char in str(sys.stdin.readline())]
	ouvert = 0
	change = 0
	for i in range(n):
		if string[i] == '(':
			ouvert += 1
		else:
			ouvert -= 1
		if ouvert < 0:
			string[i] = '('
			ouvert += 1
			change += 1
	print(change)


test_case = int(input())
for _ in range(test_case):
	n = int(input())
	seq = input()
	seq = seq[::-1]
	op = 0
	close = 0
	moves = 0
	for i in seq:
		if i == '(':
			op += 1
		if i == ')':
			close += 1
		if op > close:
			moves += 1
			op -= 1
		elif op == close:
			op = 0
			close = 0
	print(moves)


t = int(input())
for h in range(t):
	n = int(input())
	s = str(input())
	dp = [0]
	for i in s:
		if i == ')':
			dp.append(max(0, dp[-1] - 1))
		elif i == '(':
			dp.append(dp[-1] + 1)
	print(dp[-1])


for i in range(int(input())):
	n = int(input())
	s = list(input())
	leftIndex = 0
	rightIndex = n - 1
	while len(s) > 0:
		leftIndex = s.index('(')
		rightIndex = leftIndex + 1
		while rightIndex < len(s):
			if s[rightIndex] == ')':
				break
			else:
				rightIndex += 1
		if leftIndex > rightIndex or rightIndex >= len(s):
			break
		s.pop(rightIndex)
		s.pop(leftIndex)
	print(len(s) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()[:n]
	close = 0
	stack = []
	for i in s:
		if i == ')':
			if len(stack) != 0:
				x = stack.pop()
			else:
				close += 1
		else:
			stack.append(i)
	print(close)


t = int(input())
for _ in range(t):
	n = int(input())
	x = input()
	l = [-1]
	for i in range(n):
		if x[i] == '(':
			l.append('(')
		if x[i] == ')' and l[-1] != -1:
			l.pop()
	print(len(l) - 1)


t = int(input())
n = 0
niz = ''
stacked = 0
sol = [0 for i in range(t)]
i = 0
while i < t:
	sol[i] = 0
	n = int(input())
	niz = input()
	while n > 0:
		n -= 1
		if niz[n] == '(':
			if stacked == 0:
				sol[i] += 1
			else:
				stacked -= 1
		else:
			stacked += 1
	stacked = 0
	i += 1
i = 0
while i < t:
	print(sol[i])
	i += 1


t = int(input())
while t > 0:
	n = int(input())
	p = input()
	s = r = 0
	for i in range(0, n):
		if p[i] == '(':
			s = s + 1
		else:
			s = s - 1
			if s < 0:
				s = 0
				r = r + 1
	print(r, end='\n')
	t = t - 1


t = int(input())
for _ in range(t):
	move_count = 0
	n = int(input())
	s = input()
	ob_count = 0
	for i in s:
		if i == '(':
			ob_count += 1
		elif ob_count > 0:
			ob_count -= 1
		else:
			move_count += 1
	print(move_count)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	opening = 0
	steps = 0
	for char in s:
		if char == '(':
			opening += 1
		elif opening > 0:
			opening -= 1
		else:
			steps += 1
	print(steps)


from math import *
from collections import *
from bisect import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input().rstrip('\n')
	r = 0
	(cl, op) = (0, 0)
	for i in s:
		if i == '(':
			op += 1
			if cl:
				cl -= 1
				op -= 1
		else:
			cl += 1
			if cl > op:
				r += 1
				cl -= 1
			elif op:
				cl -= 1
				op -= 1
	print(r)


for t in range(int(input())):
	n = int(input())
	s = input()
	(ans, open) = (0, 0)
	for c in s:
		if c == ')':
			open -= 1
			if open < 0:
				ans += 1
				open = 0
		else:
			open += 1
	print(ans)


n = int(input(''))
matrix = []
for i in range(n):
	x = int(input(''))
	matrix.append(input(''))
for k in range(n):
	t = list(matrix[k])
	for j in range(len(t)):
		if t[j] == '(':
			t[j] = 1
		else:
			t[j] = 0
	cnt = 0
	i = 0
	while i < len(t):
		if t[i] == 0:
			if i == 0:
				del t[i]
				cnt = cnt + 1
				continue
			cnt0 = t[0:i].count(0)
			cnt1 = t[0:i].count(1)
			if cnt0 == cnt1:
				cnt = cnt + 1
				del t[i]
			else:
				i = i + 1
		else:
			i = i + 1
	print(cnt)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import sqrt, ceil, factorial, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from decimal import Decimal
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	s = list(data())
	stack = []
	answer = 0
	for i in s:
		if i == '(':
			stack.append('(')
		elif not stack:
			answer += 1
		else:
			stack.pop()
	out(min(n - answer, answer))


t = int(input())
for _ in range(t):
	n = int(input())
	seq = list(input())
	stack = []
	count = 0
	i = 0
	while i < len(seq):
		char = seq[i]
		if char == '(':
			stack.append('(')
		elif stack:
			stack.pop()
		else:
			count += 1
			seq.append(')')
		i += 1
	print(count)


a = int(input())
c1 = 0
c2 = 0
for i in range(a):
	b = int(input())
	c = input()
	for j in c:
		if j == '(':
			c1 += 1
		elif j == ')':
			if c1 > 0:
				c1 -= 1
				c2 += 2
	print((b - c2) // 2)
	c2 = 0
	c1 = 0


for t in range(int(input())):
	n = int(input())
	s = input()
	prefix = [0] * (n + 1)
	mn = 0
	for i in range(n):
		if s[i] == '(':
			prefix[i + 1] = prefix[i] + 1
		if s[i] == ')':
			prefix[i + 1] = prefix[i] - 1
		mn = min(mn, prefix[i + 1])
	print(-1 * mn)


from collections import deque
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	d = deque(list(s))
	e = deque([])
	cnt = 0
	while d:
		tmp = d.popleft()
		if tmp == ')':
			if len(e) == 0:
				d.append(tmp)
				cnt += 1
			else:
				e.pop()
		else:
			e.append(tmp)
	print(cnt)


for i in range(int(input())):
	n = int(input())
	k = 0
	tim = 0
	for n in input():
		if n == '(':
			k += 1
		elif k == 0:
			tim += 1
		else:
			k -= 1
	print(tim)


tc = int(input())
for _ in range(tc):
	n = int(input())
	breackets = list(input())
	moves = 0
	while breackets[0] == ')':
		breackets.pop(0)
		breackets.append(')')
		moves += 1
	stack = []
	i = 0
	while i < len(breackets):
		if breackets[i] == '(':
			stack.append(1)
			i += 1
		elif len(stack) > 0:
			stack.pop(0)
			i += 1
		else:
			breackets.pop(i)
			breackets.append(')')
			moves += 1
	print(moves)


for _ in range(int(input())):
	n = int(input())
	ar = list(input())
	kek = 0
	ans = 0
	for i in range(n):
		if ar[i] == '(':
			kek += 1
		else:
			kek -= 1
		if kek < 0:
			kek += 1
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(input())
	su = 0
	ans = []
	if l[0] == '(':
		ans.append(1)
	else:
		ans.append(-1)
	for i in range(1, n):
		if l[i] == ')':
			ans.append(ans[-1] - 1)
		elif ans[-1] < 0:
			ans.append(1)
		else:
			ans.append(ans[-1] + 1)
	c = 0
	for i in range(n):
		if ans[i] < 0:
			c += 1
	print(c)


test = int(input())
for t in range(test):
	n = int(input())
	s = input()
	l = []
	for i in s:
		if i == '(':
			l.append(i)
		elif len(l) != 0:
			l.pop()
	print(len(l))


def one_case():
	n = int(input())
	s = input()
	ll = len(s)
	t = 0
	move = 0
	for i in range(ll):
		j = ll - 1 - i
		if t == 0 and s[j] == '(':
			move += 1
			continue
		t += 1 if s[j] == ')' else -1
	print(t)
t = int(input())
for i in range(t):
	one_case()


import sys
inp = [x for x in sys.stdin.read().split()]
ii = 0
ttt = int(inp[ii])
ii += 1
for _ in range(ttt):
	n = int(inp[ii])
	ii += 1
	s = inp[ii]
	ii += 1
	(b, minb) = (0, 0)
	for c in s:
		if c == '(':
			b += 1
		else:
			b -= 1
		minb = min(minb, b)
	print(-minb)


t = int(input())
for _ in range(t):
	n = int(input())
	m = n // 2
	s = str(input())
	d = 0
	mn = float('inf')
	for x in s:
		if x == '(':
			d += 1
		else:
			d -= 1
		mn = min(d, mn)
	if mn < 0:
		print(-mn)
	else:
		print(0)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	n = int(input())
	string = [x for x in input()]
	stack = []
	c = 0
	for x in string:
		if x == '(':
			stack.append(x)
		elif len(stack):
			stack.pop()
		else:
			c += 1
	print((c + len(stack)) // 2)


import math
import os
import random
import re
import sys
from collections import defaultdict
case = int(input())
for i in range(case):
	strLen = int(input())
	inpStr = input().strip()
	cnt = 0
	stck = []
	for ch in inpStr:
		if ch == '(':
			stck.append('(')
		elif len(stck) == 0 or stck[-1] == ')':
			stck.append(')')
		else:
			stck.pop()
	print(len(stck) // 2)


def f(x, k):
	x1 = list(x)
	i = 0
	while i < len(x1) - 1:
		if x1[i] == '(' and x1[i + 1] == ')':
			x1.pop(i + 1)
			x1.pop(i)
			i = 0
		else:
			i += 1
	print(len(x1) // 2)
n = int(input())
for i in range(n):
	k = int(input())
	x = input()
	f(x, k)


for a in [*open(0)][2::2]:
	r = c = 0
	for x in a[:-1]:
		c += 2 * ord(x) - 81
		r += c > r
	print(r)


n = int(input())
for _ in range(n):
	a = int(input())
	s = input()
	ccount = 0
	ans = 0
	for i in range(a):
		if s[i] == '(':
			ccount = ccount + 1
		else:
			ccount = ccount - 1
		if ccount < 0:
			ans = ans + 1
			ccount = 0
	print(ccount)


t = int(input())
for i in range(t):
	input()
	a = input()
	while a != '' and a.find('()') != -1:
		a = ''.join(a.split('()'))
	print(len(a) // 2)


t = int(input())
for i in range(t):
	s = int(input())
	st = input()
	reg = 0
	ans = 0
	for c in range(len(st)):
		if st[c] == '(':
			reg += 1
		elif reg <= 0:
			ans += 1
		else:
			reg -= 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s1 = input()
	s = ['$']
	for i in s1:
		if i == ')' and s[-1] == '(':
			s.pop()
			continue
		s.append(i)
	k = 0
	s = s[1:]
	n = len(s)
	for i in range(n // 2, n):
		if s[i] == '(':
			k += 1
	for i in range(k, n // 2):
		if s[i] == ')':
			k += 1
	print(k)


def main():
	n = int(input())
	s1 = str(input())
	cnt = 0
	ans = 0
	for i in range(len(s1)):
		if s1[i] == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			cnt = 0
			ans += 1
	print(cnt)
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = '()'
	for c in s:
		s = s.replace('()', '')
	print(len(s) // 2)


for i in range(int(input())):
	input()
	x = 0
	ans = 0
	for j in input():
		if j == ')':
			if x == 0:
				ans += 1
			else:
				x -= 1
		else:
			x += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	opening = 0
	closing = 0
	moves = 0
	i = 0
	while i < n:
		if s[i] == '(':
			opening += 1
		if s[i] == ')':
			closing += 1
			if closing > opening + moves:
				moves += 1
		i += 1
	print(moves)


def tran(s):
	S = []
	for i in s:
		S.append(i)
	c = 0
	x = 'ss'
	i = 0
	while i < len(S):
		if S[i] == ')':
			pass
		else:
			for j in range(i + 1, len(S)):
				if S[j] == ')':
					S.pop(j)
					c = c + 1
					break
		i += 1
	return int((len(s) - 2 * c) / 2)
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	res = tran(s)
	ans.append(res)
for i in ans:
	print(i)


import math
T = int(input())
for _ in range(T):
	n = int(input())
	Str = input()
	stack = []
	for i in Str:
		if len(stack) == 0:
			stack.append(i)
		elif i == ')' and stack[-1] == '(':
			stack.pop(-1)
		else:
			stack.append(i)
	print(len(stack) // 2)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()[:-1]
	l = 0
	for i in range(n):
		if s[i] == '(':
			l += 1
		elif l > 0:
			l -= 1
	print(l)


t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	num = 0
	moves = 0
	for i in s:
		num += int(i == '(') - int(i == ')')
		moves = min(moves, num)
	print(abs(moves))


t = int(input())
strings = []
for i in range(t):
	n = int(input())
	strings.append(input())
output = []
counter = 0
count = 0
for ss in strings:
	for s in ss:
		if s == '(':
			counter += 1
		elif counter != 0:
			counter -= 1
		else:
			count += 1
	output.append(counter)
	counter = 0
for x in output:
	print(x)


def solve(arr, n):
	steps = 0
	count = 0
	for i in arr:
		count += 1 if i == '(' else -1
		if count < 0:
			steps += 1
			count += 1
	print(steps)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(input())
	solve(arr, n)


import math
for _ in range(int(input())):
	n = int(input())
	s = input()
	ans1 = 0
	ans2 = 0
	for i in range(0, len(s)):
		if s[i] == '(':
			ans1 += 1
		elif s[i] == ')':
			if ans1 > 0:
				ans1 -= 1
			else:
				ans2 += 1
	if ans1 == ans2:
		print(ans1)
	else:
		print(abs(ans1 - ans2))


t = int(input())
for _ in range(t):
	n = int(input())
	changes = 0
	opens = 0
	counts = 0
	sequence = list(input())
	for char in sequence:
		if char == '(':
			opens += 1
		elif opens > 0:
			opens -= 1
		else:
			sequence.append(')')
			counts += 1
	print(counts)


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	i = 0
	an = 0
	c = 0
	while i < n:
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			an += 1
			c += 1
		i += 1
	print(an)


x = int(input())
while x:
	x -= 1
	num = input()
	s = input()
	moves = 0
	left = []
	for i in s:
		openPos = s.find('(')
		closePos = s.find(')')
		if openPos > closePos:
			left.append('(')
			s = s[1:]
		else:
			s = s[:closePos] + s[closePos + 1:]
			s = s[:openPos] + s[openPos + 1:]
	print(len(left) // 2)


def DeleteChar(s, h):
	return s[:h] + s[h + 1:]
n = int(input())
TestCases = []
strings = []
for i in range(0, n, 1):
	TestCases.append(int(input()))
	strings.append(input())
for i in range(0, n, 1):
	k = 0
	while k < TestCases[i]:
		if strings[i][k] == '(':
			for j in range(k + 1, TestCases[i], 1):
				if strings[i][j] == ')':
					strings[i] = DeleteChar(strings[i], k)
					strings[i] = DeleteChar(strings[i], j - 1)
					TestCases[i] = len(strings[i])
					k = -1
					break
		k += 1
	print(TestCases[i] // 2)


def solve():
	n = int(input())
	s = list(input())
	i = 0
	while i < len(s) - 1:
		if s[i] == '(' and s[i + 1] == ')':
			s.pop(i + 1)
			s.pop(i)
			if i >= 1:
				i -= 1
			continue
		i += 1
	print(len(s) // 2)

def main():
	n = int(input())
	while n > 0:
		solve()
		n -= 1
main()


t = int(input())
s = ''
count = 0
prev = 0
res = []
l = []
for i in range(t):
	n = int(input())
	s = input()
	l.append(s)
for i in l:
	for j in range(len(i) - 1):
		if i[j] == '(':
			count += 1
		elif i[j] == ')':
			count -= 1
		if count < prev:
			prev = count
	res.append(prev)
	count = 0
	prev = 0
for i in res:
	print(-i)


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	l = [0]
	for i in a:
		if i == '(':
			l.append(i)
		elif l[-1] == '(' and i == ')':
			l.pop(-1)
		else:
			l.append(-1)
	print((len(l) - 1) // 2)


for _ in range(int(input())):
	n = int(input())
	arr = list(input())
	que = []
	for i in arr:
		if len(que) == 0:
			que.append(i)
		elif que[-1] == '(' and i == ')':
			que.pop()
		else:
			que.append(i)
	print(len(que) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = ['']
	not_matched = 0
	for i in s:
		if i == ')':
			if stack[-1] == '(':
				stack.remove(stack[-1])
			else:
				stack.append(i)
		else:
			stack.append(i)
	print((len(stack) - 1) // 2)


import sys

def getK(s):
	oCount = 0
	cCount = 0
	for a in s:
		if ')' == a:
			if oCount > 0:
				oCount -= 1
			else:
				cCount += 1
		else:
			oCount += 1
	return oCount
data = sys.stdin.readlines()
data.pop(0)
odd = True
for line in data:
	odd = not odd
	if odd:
		if not '' == line.rstrip():
			print(getK(line.rstrip()))


import sys
input = lambda : sys.stdin.readline().rstrip()
inp = sys.stdin.buffer.readline

def I():
	return list(map(int, inp().split()))
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	for i in s:
		if st:
			if st[-1] != i and st[-1] == '(':
				st.pop()
			else:
				st.append(i)
		else:
			st.append(i)
	print(len(st) // 2)


t = int(input())
while t:
	t = t - 1
	n = int(input())
	s = input()
	flag = 0
	cnt = 0
	x = s
	for i in range(n):
		if x[i] == ')':
			flag -= 1
		else:
			flag += 1
		if flag < 0:
			cnt += 1
			flag = 0
	print(cnt)


testcases = int(input())
testlist = []
for i in range(testcases):
	slength = int(input())
	s = input()
	testlist.append(s)

def minimizer(sequence):
	moves = 0
	bal = 0
	for i in sequence:
		if i == '(':
			bal += 1
		elif i == ')':
			bal -= 1
		if bal < 0:
			moves += 1
			bal += 1
	return moves
for i in testlist:
	print(minimizer(i))


t = int(input())
for i in range(t):
	n = int(input())
	brackets = list(input())
	poscnt = 0
	totalcnt = 0
	for k in brackets:
		if k == '(':
			poscnt += 1
		elif poscnt == 0:
			totalcnt += 1
		else:
			poscnt -= 1
	print(totalcnt)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	x = s.count(')')
	y = s.count('(')
	if x == y:
		print(x)
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	lst = input()
	cnt = 0
	stack = []
	for s in lst:
		if s == '(':
			stack.append(1)
		elif len(stack) == 0 and s == ')':
			cnt += 1
		elif s == ')':
			stack.pop()
	print(cnt)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	s = input().strip()
	an = 0
	k = c = p = 0
	for i in range(n):
		if s[i] == '(':
			k += 1
			p += 1
		else:
			if p > 0:
				c += 1
				p -= 1
			k -= 1
	print((n - 2 * c) // 2)


from math import sqrt
for t in range(int(input())):
	n = int(input())
	s = input()
	k = 0
	c = 1
	a = []
	for i in s:
		if i == '(':
			k += 1
		elif i == ')':
			k -= 1
		if k < 0:
			a.append(k)
	if len(a) == 0:
		print(0)
		continue
	m = a[0]
	for i in range(1, len(a)):
		if a[i] < m:
			c += 1
			m = a[i]
	print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	lol = 0
	ans = 0
	for elem in s:
		if elem == '(':
			lol += 1
		else:
			lol -= 1
		if lol < 0:
			ans = max(ans, abs(lol))
	print(ans)


I = input
import math
for _ in range(int(I())):
	n = int(I())
	s = I()
	ans = 0
	c = 0
	for i in range(n):
		if s[i] == ')':
			if c == 0:
				ans += 1
				continue
			c -= 1
		else:
			c += 1
	ans += c
	print(ans // 2)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
import math
from functools import reduce

def gift():
	for _ in range(t):
		n = int(input())
		string = input()
		ans = 0
		left = 0
		for i in range(n):
			if string[i] == '(':
				left += 1
			else:
				left -= 1
				if left < 0:
					ans += 1
					left = 0
		yield ans
t = int(input())
ans = gift()
print(*ans, sep='\n')


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	pilha = []
	for b in s:
		if not len(pilha):
			pilha.append(b)
		elif b == ')' and pilha[-1] == '(':
			pilha.pop()
		else:
			pilha.append(b)
	print(len(pilha) // 2)


t = int(input())
while t:
	n = int(input())
	s = input()
	s = list(s)
	c = 0
	st = []
	for i in range(len(s)):
		if s[i] == ')':
			if st == [] or st[-1] == ')':
				c += 1
				st.append(s[i])
			elif st != [] and st[-1] == '(':
				st.pop()
		else:
			st.append(s[i])
	print(c)
	t -= 1


t = int(input())
fridge = list()
fridge_answer = list()
for i in range(t):
	d = input()
	fridge.append(input())
for i in range(len(fridge)):
	s = fridge[i]
	while '()' in s:
		s = s.replace('()', '')
	if '(' in s and ')' in s:
		s = s.strip('(')
		print(len(s))
	else:
		print(len(s))


for _ in range(int(input())):
	n = int(input())
	s = input()
	c1 = 0
	c2 = 0
	for item in s:
		if item == '(':
			c1 += 1
		elif c1 > 0:
			c1 -= 1
		else:
			c2 += 1
	print(c1)


from sys import stdin
t = int(input())
for ts in range(t):
	n = int(input())
	s = input()
	p = []
	ans = 0
	for i in range(n):
		if s[i] == '(':
			p.append(i)
		elif len(p) > 0:
			p.pop()
		else:
			ans += 1
	print(ans)


def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		s = input()
		otk = 0
		ans = 0
		for item in s:
			if item == '(':
				otk += 1
			elif otk > 0:
				otk -= 1
			else:
				ans += 1
		print(ans)
main()


from sys import stdin, stdout
import math
input = stdin.readline

def print(x='', y='', end='\n'):
	if y == '':
		stdout.write(str(x) + end)
	else:
		stdout.write(str(x) + ' ' + str(y) + end)

def solve():
	n = int(input())
	s = input()
	ans = 0
	(o, c) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			o += 1
		else:
			c += 1
			if c > o:
				ans += 1
				c -= 1
	print(ans)
tt = 1
tt = int(input())
for __ in range(tt):
	solve()


def solution():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		cnt = 0
		ans = 0
		for i in range(n):
			if s[i] == ')':
				cnt -= 1
			else:
				cnt += 1
			ans = min(ans, cnt)
		print(abs(ans))
solution()


from sys import stdin, stdout

def input():
	return stdin.readline().strip()

def ans(s):
	counter = 0
	seq = []
	for c in s:
		if c == '(':
			counter += 1
		else:
			counter -= 1
		seq += [counter]
	return -min(seq)
T = int(input())
for _ in range(T):
	input()
	print(ans(input()))


ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
for _ in range(ii()):
	n = ii()
	a = list(si())
	c = 0
	p = 0
	for i in range(0, n):
		if a[i] == '(':
			c = c + 1
		elif a[i] == ')':
			if c == 0:
				p = p + 1
			else:
				c = c - 1
	print(p)


def checkBalance(mystr):
	arr = []
	i = 0
	for mystr[i] in mystr:
		if mystr[i] == '(':
			arr.append(mystr[i])
		elif not arr and mystr[i] == ')':
			return False
		elif i and mystr[i] == ')' and (arr[-1] == '('):
			arr.pop()
		else:
			return False
		i += 1
	if arr:
		return False
	else:
		return True
for i in range(int(input())):
	n = int(input())
	s = list(input())
	c = 0
	while not checkBalance(s):
		c += 1
		i = 0
		for s[i] in s:
			if s[i] == ')':
				b = s.pop(i)
				s.append(b)
				break
			i += 1
	else:
		print(c)


def solve():
	n = int(input())
	s = input()
	n1 = 0
	for i in s:
		if i == '(':
			n1 += 1
		else:
			n1 -= 1
		n1 = max(n1, 0)
	print(n1)
for i in range(int(input())):
	solve()


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	unpaired = 0
	for i in range(n):
		if s[i] == '(':
			stack.append(s[i])
		elif len(stack) == 0:
			unpaired += 1
		elif stack[-1] == ')':
			unpaired += 1
		else:
			del stack[-1]
	unpaired += len(stack)
	print(unpaired // 2)


from collections import deque

def solve():
	n = int(input())
	S = list(input())
	stack = deque([])
	for ch in S:
		if ch == ')':
			if len(stack) == 0 or stack[-1] != '(':
				stack.append(ch)
			else:
				stack.pop()
		else:
			stack.append(ch)
	print(len(stack) // 2)
t = int(input())
while t > 0:
	solve()
	t -= 1


t = int(input())
for _ in range(t):
	(n,) = map(int, input().split())
	s = input()
	dep = 0
	mov = 0
	for i in s:
		if i == '(':
			dep += 1
		elif dep == 0:
			mov += 1
		else:
			dep -= 1
	print(mov)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	changes = 0
	counter = 0
	for c in s:
		if c == '(':
			counter += 1
		else:
			counter -= 1
		if counter < 0:
			changes += 1
			counter += 1
	print(changes)


for _ in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for ch in s:
		if ch == '(':
			c += 1
		elif c >= 1:
			c -= 1
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(k, cont, final) = (len(s), 0, 0)
	for i in range(k):
		if s[i] == '(':
			cont += 1
		else:
			cont -= 1
		if cont < 0:
			final += 1
			cont = 0
	print(max(cont, final))


for _ in range(int(input())):
	a = int(input())
	s = input()
	balmin = 0
	bal = 0
	for i in s:
		if i == '(':
			if balmin > bal:
				balmin = bal
			bal += 1
		else:
			bal -= 1
	print(abs(balmin))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count = 0
	openBrac = 0
	closedBrac = 0
	for i in s:
		if i == '(':
			openBrac += 1
		elif i == ')':
			if openBrac > 0:
				openBrac -= 1
			else:
				count += 1
	print(count)


for _ in range(0, int(input())):
	n = int(input())
	string = input()
	for _ in range(int(n / 2)):
		string = string.replace('()', '')
	s = sum(list(map(lambda x: x == ')', list(string))))
	print(s)


line = input()
for c in range(1, int(line) + 1):
	no = int(input())
	arr = list(input())
	ind = 0
	l = no / 2
	r = no / 2
	for i in range(0, no):
		if arr[i] == ')':
			if r > l:
				r -= 1
		else:
			l -= 1
	print(int(r - l))


t = int(input())
for i in range(0, t):
	total = int(int(input()) / 2)
	val = str(input())
	stack = []
	count = 0
	for i in range(0, len(val)):
		if val[i] == '(':
			stack.append(val[i])
		elif len(stack) != 0 and val[i] == ')':
			stack.pop()
			count = count + 1
	print(total - count)


t = int(input())
for j in range(t):
	n = int(input())
	s = input()
	k = 0
	i = 0
	c = 0
	while True:
		if i == n + c:
			break
		elif s[i] == '(':
			k = k + 1
		elif k > 0:
			k = k - 1
		elif k == 0:
			s = s + ')'
			c += 1
		i += 1
	print(c)


import os
from sys import stdin

def solve(tc):
	n = int(stdin.readline().strip())
	s = stdin.readline().strip()
	cnt = 0
	reserve = 0
	for i in range(n):
		if s[i] == '(':
			cnt += 1
		elif cnt == 0:
			reserve += 1
		else:
			cnt -= 1
	print(reserve)
tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
	solve(tc)
	tc += 1


open_list = ['[', '{', '(']
close_list = [']', '}', ')']

def check(myStr):
	stack = []
	for i in myStr:
		if i in open_list:
			stack.append(i)
		elif i in close_list:
			pos = close_list.index(i)
			if len(stack) > 0 and open_list[pos] == stack[len(stack) - 1]:
				stack.pop()
			else:
				return False
	if len(stack) == 0:
		return True
	else:
		return False
for i in range(int(input())):
	n = int(input())
	s = list(input())
	c = 0
	while not check(s):
		c += 1
		i = 0
		for s[i] in s:
			if s[i] == ')':
				b = s.pop(i)
				s.append(b)
				break
			i += 1
	else:
		print(c)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(c1, c2, count) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			c1 += 1
		else:
			c2 += 1
		if c2 > c1:
			count += 1
			c2 -= 1
	print(count)


for t in range(int(input())):
	n = int(input())
	s = input()
	(op, cl, count) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			op += 1
		else:
			cl += 1
			if op > 0:
				op -= 1
			else:
				count += 1
	print(count)


from sys import stdin, stdout
from bisect import bisect, bisect_left, bisect_right

def gt():
	return map(int, stdin.readline().split())

def gi():
	return int(stdin.readline())

def gl():
	return list(map(int, stdin.readline().split()))

def gs():
	return stdin.readline()
t = gi()
for _ in range(t):
	n = gi()
	s = gs()
	(count1, count2) = (0, 0)
	ans = 0
	for i in range(n - 1, -1, -1):
		if s[i] == ')':
			count2 += 1
		else:
			count1 += 1
		if count1 > count2:
			ans += 1
			count1 = count2
	print(ans)


t = int(input())
for hatt in range(t):
	n = int(input())
	s = input()
	coun = 0
	num = 0
	for i in s:
		if i == ')':
			coun -= 1
		else:
			coun += 1
		if coun < 0:
			coun = 0
			num += 1
	print(num)


t = int(input())
for i in range(t):
	n = int(input())
	brackets = input()
	memory = []
	result = 0
	for b in brackets:
		if b == '(':
			memory.append(b)
		elif b == ')':
			if not memory:
				result += 1
			else:
				memory.pop()
	print(result)


t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	old = float('inf')
	moves = 0
	while s:
		if old == len(s):
			moves += 1
			s = s[1:] + s[0]
		old = len(s)
		s = s.replace('()', '')
	print(moves)


def solve():
	x = int(input())
	string = input()
	counter = 0
	total_closed = 0
	for ch in string:
		if ch == '(':
			counter += 1
		elif ch == ')':
			counter -= 1
		if counter < 0:
			total_closed += 1
			counter = 0
	print(total_closed)
t = int(input())
for _ in range(t):
	solve()


for i in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	bal = 0
	for i in range(n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			bal = 0
			ans += 1
	print(ans)


t = int(input())
while t:
	n = int(input())
	brac = input()
	count = 0
	ans = 0
	x = 0
	while True:
		if brac[x] == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			brac = brac[:x] + brac[x + 1:] + brac[x]
			count += 1
			ans += 1
		else:
			x += 1
		if x == n:
			print(ans)
			break
	t -= 1


test = int(input())
for ii in range(test):
	n = int(input())
	st = input()
	count = 0
	while False:
		break
	x = 0
	for j in range(n):
		if st[j] == '(':
			x += 1
		elif x <= 0:
			count += 1
		else:
			x -= 1
	print(count)


t = int(input())
result = []
for i in range(t):
	n = int(input())
	arr = input()
	moves = 0
	k = 0
	for j in range(n):
		if arr[j] == '(':
			k += 1
		elif k == 0:
			moves += 1
		else:
			k -= 1
	result.append(moves)
for i in range(t):
	print(result[i])


def solve(s):
	balance = 0
	cnt = 0
	for i in range(0, len(s)):
		if s[i] == '(':
			balance += 1
		else:
			balance -= 1
			if balance < 0:
				balance = 0
				cnt += 1
	return cnt
t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	print(solve(s))


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	moves = 0
	state = 0
	for i in range(n):
		if s[i] == '(':
			if state < moves:
				moves = state
			state += 1
		elif s[i] == ')':
			state -= 1
		i += 1
	print(moves * -1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count = 0
	output = 0
	for i in s:
		if i == ')':
			count -= 1
		else:
			count += 1
		output = min(output, count)
	print(abs(output))


num = int(input())
for x in range(num):
	x = int(input())
	s = input()
	lst = list()
	for i in s:
		if i == '(':
			lst.append('(')
		elif len(lst) == 0:
			continue
		else:
			lst.remove(lst[0])
	print(len(lst))


class Stack:

	def __init__(self):
		self.items = []

	def is_empty(self):
		return self.items == []

	def push(self, item):
		self.items.append(item)

	def pop(self):
		return self.items.pop()

	def peek(self):
		return self.items[len(self.items) - 1]

	def size(self):
		return len(self.items)
t = int(input())
for j in range(t):
	a = int(input())
	s1 = []
	s2 = Stack()
	count = 0
	x = input()
	for symbols in x:
		s1.append(symbols)
	for brackets in s1:
		if brackets == '(':
			s2.push(brackets)
		elif brackets == ')':
			try:
				s2.pop()
			except IndexError:
				count = count + 1
				continue
		else:
			continue
	print((s2.size() + count) // 2)


n = int(input())
for i in range(n):
	m = int(input())
	l = list(input())
	c = 0
	o = 0
	for i in range(m):
		if l[i] == '(':
			o += 1
		elif l[i] == ')':
			if o > 0:
				o -= 1
			else:
				c += 1
	print(c)


for i in range(int(input())):
	l = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = result = 0
	for i in s:
		if i == '(':
			l += 1
		else:
			l -= 1
			if l < 0:
				result += 1
				l = 0
	print(result)


def solve(n, s):
	op = 0
	res = 0
	for c in s:
		if c == '(':
			op += 1
		else:
			op -= 1
			if op < 0:
				op = 0
				res += 1
	return res
t = int(input())
for i_t in range(t):
	n = int(input())
	s = input()
	print(solve(n, s))


from sys import stdin
N = int(stdin.readline())
for case in range(N):
	_ = input()
	x = stdin.readline()
	x = [i for i in x]
	fp = 0
	mov = 0
	for i in x:
		if i == '(':
			fp += 1
		elif i == ')':
			if fp > 0:
				fp -= 1
			else:
				x.append(i)
				mov += 1
	print(mov)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	x = 0
	y = 0
	z = 0
	for i in range(n):
		if s[i] == '(':
			x += 1
		elif s[i] == ')':
			y += 1
		if y > x:
			z += 1
			x = 0
			y = 0
	print(z)


def solve(s):
	while s.find('()') != -1:
		s = s.replace('()', '')
	i = len(s) // 2
	return i
tests = int(input())
ans = []
for i in range(tests):
	n = int(input())
	s = input()
	print(solve(s))


t = int(input())
for tit in range(t):
	n = int(input())
	s = input()
	i = 0
	moves = 0
	opens = 0
	while i < n:
		if s[i] == '(':
			opens += 1
		elif opens > 0:
			opens -= 1
		else:
			br = s[i]
			s = s[:i] + s[i + 1:] + br
			moves += 1
			i -= 1
		i += 1
	print(moves)


cases = int(input())
for t in range(cases):
	n = int(input())
	s = input()
	a = []
	for i in s:
		if i == ')':
			if a:
				if a[-1] == '(':
					a.pop()
				else:
					a.append(i)
		else:
			a.append(i)
	print(len(a))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	hasOpen = 0
	unmatched = 0
	for i in s:
		if i == ')' and (not hasOpen):
			unmatched += 1
		elif i == '(':
			hasOpen += 1
		elif i == ')':
			hasOpen -= 1
	print(unmatched)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	st = []
	for char in s:
		if char == '(':
			st.append(char)
		elif st and st[-1] == '(':
			st.pop()
		else:
			st.append(char)
	print(len(st) // 2)
	t -= 1


def solve(n, s):
	st = [')']
	cnt = 0
	for b in s:
		if b == ')':
			if st[-1] == '(':
				st.pop()
			else:
				cnt += 1
		else:
			st.append(b)
	return cnt
for _ in range(int(input().strip())):
	n = int(input().strip())
	s = input().strip()
	print(solve(n, s))


def go(ls):
	s = []
	open = '('
	for i in ls:
		if i == open:
			s += (i,)
		elif not s or s[-1] == ')':
			s += (')',)
		else:
			s.pop()
	return len(s) // 2
t = int(input())
for i in range(t):
	t = int(input())
	ls = input()
	print(go(ls))


from sys import *
t = int(stdin.readline())
while t > 0:
	n = int(stdin.readline())
	s = stdin.readline()
	st = []
	count = 0
	for i in s:
		if i is '(':
			st.append(i)
		elif i is ')' and len(st) > 0:
			st.pop()
		elif i is ')' and len(st) == 0:
			s + ')'
			count += 1
	print(count)
	t -= 1


import sys
input = sys.stdin.readline

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	ans = 0
	cnt = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			ans = max(ans, abs(cnt))
	print(ans)


def process(s):
	if s == '':
		return 0
	cnt = 0
	depth = 0
	i = 0
	while i < len(s):
		t = s[i]
		if t == '(':
			depth += 1
		else:
			depth -= 1
		if depth < 0:
			s = s[:i] + s[i + 1:] + ')'
			cnt += 1
			i = 0
			depth = 0
			continue
		i += 1
	return cnt
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = process(s)
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	s = input()
	opn = 0
	clo = 0
	ans = 0
	diff = 0
	for ch in s:
		if ch == '(':
			opn = opn + 1
		else:
			clo = clo + 1
			if clo - opn > diff:
				ans = ans + 1
				diff = clo - opn
	print(ans)
	t = t - 1


t = int(input())
for _ in range(t):
	n = int(input())
	lis = list(input())
	tot = 0
	erra = 0
	for i in range(n):
		if lis[i] == '(':
			tot = tot + 1
			continue
		elif tot > 0:
			tot = tot - 1
			continue
		else:
			erra = erra + 1
	print(erra)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	result = 0
	for j in s:
		if j == '(':
			result += 1
		elif result > 0:
			result -= 1
	print(result)


def regularbrakets(n, s):
	arr = list(s)
	count = 0
	i = 0
	stack = []
	while i < len(arr):
		char = arr[i]
		if char == '(':
			stack.append(char)
		elif stack:
			stack.pop()
		else:
			arr.append(char)
			count += 1
		i += 1
	return count
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(regularbrakets(n, s))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	d = []
	if s[0] == '(':
		d.append(1)
	else:
		d.append(0)
	for j in range(1, n):
		if s[j] == ')' and len(d) > 0 and (d[len(d) - 1] == 1):
			del d[len(d) - 1]
		elif s[j] == ')':
			d.append(0)
		if s[j] == '(':
			d.append(1)
	print(int(len(d) / 2))


for i in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	now = 0
	l = [i for i in s]
	i = 0
	j = 0
	while 1:
		flag = 0
		i = 0
		while 1:
			if i >= len(l) - 1:
				break
			if l[i] == '(' and l[i + 1] == ')':
				l.pop(i)
				l.pop(i)
				flag = 1
			else:
				i += 1
		if flag == 0:
			break
	print(len(l) // 2)


import os
import sys
debug = True
if debug and os.path.exists('input.in'):
	input = open('input.in', 'r').readline
else:
	debug = False
	input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
test_count = int(input())
for t in range(test_count):
	if debug:
		print('Test Case #', t + 1)
	n = inp()
	s = insr()
	cnt = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			cnt += 1
		elif s[i] == ')':
			cnt -= 1
		if cnt < 0:
			ans += 1
			cnt += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input().strip()
	while '()' in s:
		s = s.replace('()', '')
	print(min(s.count(')'), s.count('(')))


import math

def facts(n):
	ans = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			ans.append(i)
			ans.append(n // i)
	ans = sorted(ans)
	return ans
for _ in range(int(input())):
	n = int(input())
	s = str(input())
	cnt = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			cnt -= 1
			if cnt < 0:
				ans += 1
				cnt = 0
		elif s[i] == '(':
			cnt += 1
	print(ans)


def ninja(l):
	k = 0
	p = []
	for i in l:
		if i == '(':
			p.append(i)
		elif len(p) > 0 and i == ')' and (p[-1] == '('):
			p.pop()
		else:
			p.append(i)
	return len(p) // 2
for _ in range(int(input())):
	n = int(input())
	l = list(input())
	print(ninja(l))


for _ in range(int(input())):
	n = int(input())
	seq = input()
	openbra = 0
	for bra in seq:
		if bra == ')':
			if openbra > 0:
				openbra -= 1
		else:
			openbra += 1
	print(openbra)


(OP, CL) = ('(', ')')

def solve():
	global S
	S = list(S)
	sol = i = op = 0
	while i < len(S):
		if S[i] == OP:
			op += 1
		elif not op:
			S.append(S[i])
			sol += 1
		else:
			op -= 1
		i += 1
	return sol
import os
for _ in range(int(input())):
	_ = int(input())
	S = input()
	sol = solve()
	print(sol)


for _ in range(int(input())):
	n = int(input())
	a = input()
	op = 0
	ans = 0
	cl = 0
	op1 = 0
	for i in a:
		if i == '(':
			op += 1
			op1 += 1
		elif i == ')':
			op -= 1
			cl += 1
		ans = min(ans, op)
	print(abs(ans))


def step(n, s):
	st = []
	for i in range(n):
		if s[i] == '(':
			st.append(s[i])
			continue
		if len(st) == 0:
			st.append(s[i])
		elif st[len(st) - 1] == '(':
			st.pop()
			continue
		else:
			st.append(s[i])
	return len(st) // 2
T = int(input())
for t in range(T):
	num = int(input())
	s = input()
	ans = step(num, s)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	w = input()
	x = 0
	r = 0
	for i in w:
		if i == ')':
			x += 1
		else:
			x -= 1
		if x > 0:
			x = 0
			r += 1
	print(r)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	arr = []
	count = 0
	for j in s:
		if j == '(':
			arr.append(j)
		elif len(arr) == 0:
			count += 1
		else:
			arr.pop(len(arr) - 1)
	print(count)


T = int(input())
for _ in range(T):
	n = int(input())
	brackets = input().strip()
	res = 0
	worst = 0
	for bracket in brackets:
		if bracket == '(':
			res += 1
		else:
			res -= 1
			worst = min(res, worst)
	print(-worst)


t = int(input())
s = [[str] for i in range(t)]
for i in range(t):
	m = int(input())
	s[i] = input()
for i in range(t):
	p = []
	a = 0
	q = []
	for j in range(len(s[i])):
		if s[i][j] == '(':
			p.append(j)
		else:
			q.append(j)
	for j in range(int(len(s[i]) / 2)):
		for k in range(int(len(s[i]) / 2)):
			if p[j] < q[k]:
				p[j] = q[k] = -1
				break
	print(len(p) - p.count(-1))


import sys
test_num = int(sys.stdin.readline())
for test_case in range(test_num):
	num = int(sys.stdin.readline())
	colo = list(str(sys.stdin.readline()))
	left_colo = 0
	right_colo = 0
	lulu = 0
	for i in range(num):
		if colo[i] == '(':
			left_colo += 1
		else:
			right_colo += 1
		if right_colo > left_colo:
			lulu += 1
			right_colo -= 1
	print(lulu)


t = int(input())
while t:
	n = int(input())
	a = input()
	st = [a[0]]
	i = 1
	while i < len(a):
		while len(st) > 0 and i < len(a) and (a[i] == ')'):
			if st[-1] == '(':
				st.pop()
				i += 1
			else:
				st.append(a[i])
				i += 1
		if i < len(a) and len(st) == 0:
			st.append(a[i])
		elif i < len(a) and a[i] == '(':
			st.append(a[i])
		i += 1
	if len(st) == 0:
		print(0)
	else:
		print(len(st) // 2)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	v = 0
	t = 0
	for i in range(len(s)):
		if s[i] == '(':
			v += 1
		else:
			v -= 1
			if v == -1:
				t += abs(v)
				v = 0
	print(t)


n = int(input())
for j in range(n):
	k = int(input())
	s = input()
	s = list(s)
	h = [s[0]]
	for i in range(1, k):
		if h and h[-1] == '(' and (s[i] == ')'):
			h.pop()
		else:
			h.append(s[i])
	print(len(h) // 2)


import sys
cont = sys.stdin.readlines()
cont = [i.strip('\n') for i in cont]
numTests = int(cont.pop(0)[0])
cont = [i for (ind, i) in enumerate(cont) if ind % 2 == 1]

def check(string):
	kept = []
	for i in string:
		if kept == []:
			kept.append(i)
		elif kept[-1] == '(' and i == ')':
			kept.pop()
		else:
			kept.append(i)
	if len(kept) == 0:
		return True
	else:
		return False
for string in cont:
	moves = 0
	if check(string):
		print(0)
		continue
	while True:
		if string.count('()') > 0:
			string = string.replace('()', '')
		else:
			break
	if string == '':
		print(moves)
		continue
	ind = string.index(')(')
	moves += ind + 1
	print(moves)


n = 0
for _ in range(int(input())):
	l = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	acc = 0
	result = ''
	for i in s:
		if i == '(':
			acc += 1
		else:
			acc -= 1
		if acc < 0:
			result += i
			acc = 0
	print(len(result))


for _ in range(int(input())):
	n = int(input())
	brac = input()
	a = b = c = d = 0
	for i in range(len(brac)):
		if brac[i] == '(':
			a += 1
		elif a == b:
			c += 1
		else:
			b += 1
	c = c + (a - b)
	print(c // 2)


import sys
input = sys.stdin.buffer.readline

def iinp() -> int:
	return int(input())

def linp() -> list:
	return [int(p) for p in input().split()]

def sinp():
	return input().decode('unicode-escape')[0:-2]
for _ in range(iinp()):
	n = iinp()
	s = sinp()
	(sums, ans) = (0, 0)
	for c in s:
		if c == '(':
			sums -= 1
		else:
			sums += 1
		ans = max(ans, sums)
	print(ans)


def min_moving_brackets(s):
	cnt = 0
	res = 0
	for i in range(len(s)):
		if s[i] == '(':
			cnt = cnt + 1
		else:
			cnt = cnt - 1
			if cnt < 0:
				cnt = 0
				res = res + 1
	return res

def main():
	test_case = int(input())
	while test_case != 0:
		string_length = int(input())
		string_bracket = str(input())
		res = min_moving_brackets(string_bracket)
		print(res)
		test_case = test_case - 1
main()


from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	nummoves = 0
	count = 0
	for i in s:
		if i == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			nummoves += 1
			count = 0
	print(nummoves)


for _ in range(int(input())):
	n = int(input())
	s = input()
	val = 0
	res = 0
	for i in s:
		if i == ')':
			val -= 1
		else:
			val += 1
		if val < 0:
			val = 0
			res += 1
	print(res)


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
for _ in range(int(input())):
	(n, s, a, c) = (int(input()), input(), 0, 0)
	for i in range(n):
		if s[i] == ')':
			c += 1
		else:
			c -= 1
		a = max(a, c)
	print(str(a) + '\n')


for y in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	foo = 0
	for i in range(n):
		if s[i] == ')':
			if foo > 0:
				foo -= 1
			else:
				cnt += 1
		else:
			foo += 1
	print(cnt)


def main():
	for _ in range(int(input())):
		(_, r, l) = (input(), 0, [])
		for c in input():
			if c == '(':
				r -= 1
			else:
				r += 1
			l.append(r)
		print(max(l))
main()


cases = int(input())
for v in range(cases):
	n = int(input())
	s = input()
	openbracket = 0
	wrongbracket = 0
	for i in s:
		if i == '(':
			openbracket += 1
		elif i == ')' and openbracket != 0:
			openbracket -= 1
		else:
			wrongbracket += 1
	print((openbracket + wrongbracket) // 2)


from collections import deque

def solve(brackets):
	stack = deque()
	for s in brackets:
		if len(stack) > 0:
			temp = stack.pop()
			if s == ')' and temp == '(':
				pass
			else:
				stack.append(temp)
				stack.append(s)
		else:
			stack.append(s)
	return len(stack) // 2
cases = int(input())
for _ in range(cases):
	n = input()
	brackets = input()
	answer = solve(brackets)
	print(answer)


for i in range(int(input())):
	int(input())
	s = input()
	c1 = 0
	c2 = 0
	ans = 0
	tmp = 0
	for i in range(len(s)):
		if s[i] == '(':
			c1 += 1
		if s[i] == ')':
			c2 += 1
			if c2 - c1 > tmp:
				tmp = c2 - c1
				ans += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	l1 = []
	s = input()
	c = 0
	for i in s:
		if i == '(':
			l1.append(i)
		elif i == ')' and len(l1) == 0 or l1[-1] == ')':
			l1.append(i)
			c += 1
		else:
			l1.pop()
	print(c)


m = int(input())
for l in range(m):
	n = input()
	t = list(input())
	s = 0
	e = 0
	A = []
	for i in t:
		if i == '(':
			A.append(i)
		elif len(A) != 0:
			A.pop()
	print(len(A))


def count(s, n):
	prev = 10000000
	while prev > len(s):
		prev = len(s)
		s = s.replace('()', '', 1)
		if s == []:
			break
	return len(s) // 2
for i in range(int(input())):
	n = int(input())
	b = input()
	res = count(b, n)
	print(res)


from sys import stdin
from math import log
T = int(stdin.readline().strip())
for caso in range(T):
	n = int(stdin.readline().strip())
	x = stdin.readline().strip()
	ans = []
	for i in range(n):
		ans.append(x[i])
		if len(ans) >= 2 and ans[-1] == ')' and (ans[-2] == '('):
			ans.pop()
			ans.pop()
	print(len(ans) // 2)


test = int(input())
for i in range(test):
	size = int(input())
	res = []
	s = input()
	count = 0
	for j in s:
		if j == '(':
			res.append(i)
		elif j == ')' and len(res) == 0 or res[-1] == ')':
			res.append(j)
			count += 1
		else:
			res.pop()
	print(count)


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	l = n // 2 - 1
	r = n // 2
	bal = 0
	cnt = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				cnt += 1
				bal = 0
	print(cnt)


from sys import stdin
input = stdin.readline
inf = 1000000
for _ in range(int(input())):
	n = int(input())
	s = input()[:-1]
	(mn, cnt) = (inf, 0)
	for i in s:
		if i == ')':
			cnt -= 1
			mn = min(mn, cnt)
		else:
			cnt += 1
	print(-mn)


for _ in range(int(input())):
	(n, s) = (int(input()), input())
	gem = c = 0
	d = {'(': 1, ')': -1}
	for i in s:
		if gem + d[i] < 0:
			c += 1
		else:
			gem += d[i]
	print(c)


for f in [*open(0)][2::2]:
	i = g = 0
	for t in f:
		g += 2 * ord(t) - 81
		i += g > i
	print(i)


T = int(input())
for t in range(T):
	N = int(input())
	s = input()
	a = 0
	level = 0
	for c in s:
		if c == '(':
			level += 1
		elif c == ')':
			if level == 0:
				a += 1
			else:
				level -= 1
	print(a)


t = int(input())
while t > 0:
	n = int(input())
	brackets = input().strip()
	stack = []
	unended_closing_brackets = 0
	for bracket in brackets:
		if bracket == ')':
			if len(stack) == 0:
				unended_closing_brackets += 1
			elif stack[-1] != '(':
				unended_closing_brackets += 1
			else:
				stack.pop()
		else:
			stack.append(bracket)
	print(unended_closing_brackets)
	t -= 1


for i in range(int(input())):
	n = int(input())
	b = input()
	moves = brackets = 0
	for i in range(0, n):
		if b[i] == '(':
			brackets += 1
		else:
			brackets -= 1
			if brackets < 0:
				moves += 1
				brackets = 0
	print(moves)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	c = 0
	d = 0
	for i in s:
		if i == '(':
			c += 1
		elif i == ')':
			if c > 0:
				c -= 1
			else:
				ans += 1
	print(ans)


for i in range(int(input())):
	n = int(input())
	s = input()
	copen = 0
	counter = 0
	for i in s:
		if i == '(':
			copen += 1
		elif i == ')' and copen > 0:
			copen -= 1
		elif i == ')' and copen == 0:
			counter += 1
	print(counter)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	numL = 0
	ans = 0
	for i in s:
		if i == ')':
			if numL == 0:
				ans += 1
			else:
				numL -= 1
		elif numL == 0:
			numL = 1
		else:
			numL += 1
	print(ans)


t = int(input())
for q in range(t):
	n = int(input())
	s = input()
	ind = 0
	min_i = n
	for i in range(n):
		if s[i] == ')':
			ind -= 1
		else:
			ind += 1
		if ind < min_i:
			min_i = ind
	print(-min_i)


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	cnt = 0
	res = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		res = min(res, cnt)
	print(-res)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	b = []
	for j in s:
		b.append(j)
	count = 0
	j = 0
	while j < n:
		if b[j] == '(':
			count += 1
		else:
			count += -1
		if count < 0:
			count = 0
		j += 1
	print(count)


def maxLength(s, n):
	invalidOpenBraces = 0
	invalidCloseBraces = 0
	for i in range(n):
		if s[i] == '(':
			invalidOpenBraces += 1
		elif invalidOpenBraces == 0:
			invalidCloseBraces += 1
		else:
			invalidOpenBraces -= 1
	return n - (invalidOpenBraces + invalidCloseBraces)
for test in range(int(input())):
	n = int(input())
	s = input()
	matched = maxLength(s, n)
	countOpen = s.count('(')
	countOpen -= matched // 2
	print(countOpen)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, S):
	balance = 0
	endBalance = 0
	for x in S:
		if x == '(':
			balance += 1
		elif x == ')':
			balance -= 1
			if balance < 0:
				balance += 1
				endBalance -= 1
	assert balance + endBalance == 0
	return -endBalance
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N,) = [int(x) for x in input().split()]
	S = input().decode().rstrip()
	ans = solve(N, S)
	print(ans)


t = int(input())
for o in range(t):
	n = int(input())
	x = list(input())
	count = 0
	ans = 0
	i = 0
	while i < n:
		if x[i] == '(':
			count += 1
			i += 1
		else:
			count -= 1
			if count < 0:
				x.pop(i)
				x.append(')')
				count += 1
				ans += 1
			else:
				i += 1
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	while True:
		a = len(s)
		s = s.replace('()', '')
		if a == len(s):
			break
	print(a // 2)


n = int(input())
for i in range(n):
	n1 = int(input())
	x = input()
	count = 0
	count1 = 0
	for i in x:
		if i == '(':
			count += 1
		else:
			count -= 1
		if count < 0:
			count1 += 1
			count = 0
	print(count1)


n = int(input())
for _ in range(n):
	k = input()
	line = input()
	sum = min_sum = 0
	for letter in line:
		if letter == '(':
			sum += 1
		else:
			sum -= 1
			if min_sum > sum:
				min_sum = sum
	print(-min_sum)


TC = int(input())
for tc in range(TC):
	N = int(input())
	S = input()
	result = 0
	cnt = 0
	for s in S:
		if s == '(':
			cnt += 1
		elif cnt > 0:
			cnt -= 1
		else:
			result += 1
	print(result)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return len(set(factors))

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def printp(p):
	for i in p:
		print(i)
MOD = 10 ** 9 + 7
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	s = list(stdin.readline().strip('\n'))
	d = [0] * n
	if s[0] == '(':
		d[0] = 1
	else:
		d[0] = -1
	for i in range(1, n):
		if s[i] == '(':
			d[i] = d[i - 1] + 1
		if s[i] == ')':
			d[i] = d[i - 1] - 1
	print(-min(d))


def solve(n, a):
	st = [a[0]]
	c = 0
	for i in range(1, n):
		st.append(a[i])
		if len(st) >= 2 and st[-1] == ')' and (st[-2] == '('):
			c += 1
			st.pop(-1)
			st.pop(-1)
	return n // 2 - c
for _ in range(int(input())):
	n = int(input())
	a = input()
	print(solve(n, a))


i = int(input())

def parcours(s, l):
	c = 0
	for k in range(l):
		if s[k] == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			return k
	return l
for j in range(i):
	l = int(input())
	s = input()
	c = 0
	while parcours(s, l) != l:
		k = parcours(s, l)
		s = s[:k] + s[k + 1:]
		s += ')'
		c += 1
	print(c)


t = int(input())
for i in range(t):
	tamanho = int(input())
	n = input()
	s = []
	for i in range(tamanho):
		if n[i] == ')' and len(s) != 0:
			if s[0] == '(':
				s.pop(0)
			else:
				s.insert(0, n[i])
		else:
			s.insert(0, n[i])
	novo_len = len(s)
	qtd = 0
	while len(s) != 0 and s[0] == '(':
		s.pop(0)
		qtd += 1
	print(qtd)


t = int(input())
for k in range(t):
	l = int(input())
	s = input()
	stack = []
	count = 0
	i = 0
	while i < len(s):
		if s[i] == '(':
			stack.append(s[i])
			i += 1
		elif s[i] == ')' and len(stack) != 0 and (stack[-1] == '('):
			stack.pop()
			i += 1
		else:
			s = s[0:i] + s[i + 1:len(s)] + ')'
			count += 1
	print(count)


def solve(s):
	stack = []
	nWrongR = 0
	for ch in s:
		if ch == '(':
			stack.append(ch)
		elif stack and stack[-1] == '(':
			stack.pop()
		else:
			try:
				ind = stack.rindex('(')
			except:
				ind = -1
			if ind >= 0:
				del stack[ind]
			else:
				nWrongR += 1
	return nWrongR
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(solve(s))


cases = int(input())
for i in range(cases):
	length = int(input())
	seq = input()
	op = 0
	out = 0
	half = int(length / 2)
	for s in seq:
		if s == '(':
			op += 1
		if s == ')':
			op -= 1
		if op < 0:
			out += 1
			op = 0
	print(out)


import sys
import math as mt
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(o, c) = (0, 0)
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			o += 1
		else:
			c += 1
		if c > o:
			ans += 1
			c = o
	print(ans)


def check(s):
	cnt = 0
	ans = 0
	for p in s:
		if p == '(':
			cnt += 1
		else:
			cnt -= 1
		ans = min(cnt, ans)
	return abs(ans)
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	print(check(s))


import sys
from os import path
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	bal = 0
	for i in range(n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				count += 1
	print(count)


def next():
	return [int(x) for x in input().split()]
(ca,) = next()
for _ in range(ca):
	(n,) = next()
	n //= 2
	s = input()
	r = 0
	for c in s:
		if c == ')' and r > 0:
			n -= 1
			r -= 1
		elif c == '(':
			r += 1
	print(n)


for _ in range(int(input())):
	(n, s) = (input(), input())
	(ac, ans) = (0, 0)
	for c in s:
		if c == ')':
			ac -= 1
			if ac < 0:
				ans += 1
				ac = 0
		elif c == '(':
			ac += 1
	print(ans)


for _ in range(int(input())):
	a = int(input())
	b = input()
	c = 0
	ans = 0
	j = 0
	for i in b:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			c = 0
			ans += 1
			if j == 0:
				b = b[1:] + b[j]
			else:
				b = b[0:j] + b[j + 1:] + b[j]
			j -= 1
		j += 1
	print(ans)


tc = int(input())
strings = []
for i in range(1, 26):
	string = '(' * i + ')' * i
	strings.append(string)
for i in range(tc):
	length = int(input())
	mystring = input()
	for k in range(length // 2 + 2):
		for j in range(len(strings)):
			mystring = mystring.replace(strings[j], '')
	print(len(mystring) // 2)


for i in range(int(input())):
	input()
	s = list(input())
	for j in range(len(s)):
		if s[j] == '(':
			for k in range(j, len(s)):
				if s[k] == ')':
					s[j] = '-'
					s[k] = '*'
					break
	print(s.count('('))


from collections import deque
t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	p = deque()
	count = 0
	for i in range(len(a)):
		if a[i] == '(':
			p.append(a[i])
		elif len(p) != 0:
			if p[-1] == '(' and a[i] == ')':
				p.pop()
			elif p[-1] == '(' and a[i] == '(':
				p.append(a[i])
	print(len(p))


for testcase in range(int(input())):
	L = input()
	s = input()
	while 1:
		olds = s
		s = s.replace('()', '')
		if olds == s:
			break
	print(len(s) // 2)


from sys import stdin, stdout
import bisect

def st():
	return list(stdin.readline().strip())

def inp():
	return int(stdin.readline())

def li():
	return list(map(int, stdin.readline().split()))

def mp():
	return map(int, stdin.readline().split())

def pr(n):
	stdout.write(str(n) + '\n')

def soe(limit):
	l = [1] * (limit + 1)
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
			n = n - 1
		else:
			a = a * a
			n = n >> 1
	return r

def solve():
	n = inp()
	s = st()
	c = 0
	l = []
	i = 0
	while i < len(s):
		if s[i] == '(':
			l.append(s[i])
			i += 1
		elif s[i] == ')':
			if len(l) > 0 and l[-1] == '(':
				l.pop()
				i += 1
			else:
				a = s.pop(i)
				s.append(a)
				c += 1
	print(c)
for _ in range(inp()):
	solve()


n = int(input())
for i in range(n):
	lens = int(input())
	s = input()
	while lens > 0:
		s = s.replace('(())', '')
		s = s.replace('((()))', '')
		s = s.replace('()', '')
		clen = len(s)
		if clen == lens:
			break
		lens = clen
	print(lens // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	a = list(s)
	x = []
	o = 0
	c = 0
	for i in range(0, n):
		if a[i] == '(':
			o = o + 1
		else:
			o = o - 1
		if o < 0 and o < c:
			c = c - 1
	print(abs(c))


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input().rstrip()
		d = 0
		op = 0
		for x in s:
			if x == '(':
				d += 1
			else:
				d -= 1
				if d == -1:
					d = 0
					op += 1
		print(op)
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = 0
	r = 0
	c = 0
	for i in s:
		if i == ')':
			if l == 0:
				c += 1
			else:
				l -= 1
		elif i == '(':
			l += 1
	print(c)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi
import heapq

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def main():
	try:
		n = I()
		l = list(input())
		ans = 0
		(mi, ma) = (10000000.0, -1)
		for x in l:
			if x == ')':
				ans -= 1
			else:
				ans += 1
			ma = max(ans, ma)
			mi = min(ans, mi)
		print(abs(mi))
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	res = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			res += 1
		else:
			res -= 1
		if res < 0:
			res = 0
			ans += 1
	print(ans)


t = input()
t = int(t)
while t:
	t = t - 1
	n = input()
	s = input()
	lst = []
	for i in range(0, int(n)):
		if len(lst) == 0 or lst[-1] == ')':
			lst.append(s[i])
		elif s[i] == '(':
			lst.append(s[i])
		else:
			lst.pop()
	print(int(len(lst) / 2))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count_l = 0
	count_r = 0
	count = 0
	for i in range(len(s)):
		if s[i] == '(':
			count_l += 1
		else:
			count_r += 1
		if count_r > count_l:
			count_r -= 1
			count += 1
	print(count)


for case in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	cur = 0
	for c in s:
		if c == '(':
			cur += 1
		else:
			cur -= 1
			ans = min(cur, ans)
	print(abs(ans))


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	arr = []
	num = 0
	for sym in s:
		if sym == '(':
			num += 1
		else:
			num -= 1
		arr.append(num)
	ns = min(arr)
	ns = max(0, -ns)
	ans.append(ns)
for el in ans:
	print(el)


subtests = int(input())
for subtest in range(subtests):
	n = int(input())
	s = input()
	(cnt, ans) = (0, 0)
	for i in s:
		if i == ')':
			cnt -= 1
			if cnt < 0:
				cnt = 0
				ans += 1
		else:
			cnt += 1
	print(ans)


for _ in range(int(input())):
	chars = int(input())
	s = input()
	(bal, x) = (0, 0)
	for i in range(len(s) - 1):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
		x = min(x, bal)
	print(abs(x))


def brackets(s):
	stack = []
	ans = 0
	for i in s:
		if i == ')':
			if not stack:
				ans += 1
			elif stack[-1] != '(':
				ans += 1
			elif stack[-1] == '(':
				stack.pop()
		else:
			stack.append('(')
	return ans
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(brackets(s))


import sys
input = sys.stdin.buffer.readline

def iinp() -> int:
	return int(input())

def linp() -> list:
	return [int(p) for p in input().split()]

def sinp():
	return input().decode('unicode_escape')
for _ in range(iinp()):
	n = iinp()
	s = sinp()
	(sums, ans) = (0, 0)
	for c in s:
		if c == '(':
			sums -= 1
		elif c == ')':
			sums += 1
		ans = max(ans, sums)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	string = input()
	open = 0
	ans = 0
	for i in range(n):
		if string[i] == '(':
			open += 1
		else:
			open -= 1
		if open < 0:
			ans = max(ans, abs(open))
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ob = 0
	cb = 0
	move = 0
	for j in range(n):
		if cb > ob:
			move += 1
			cb -= 1
		if s[j] == '(':
			ob += 1
		else:
			cb += 1
	print(move)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	p = 0
	ans = 0
	for z in range(0, len(s)):
		if s[z] == '(':
			p += 1
		elif p > 0:
			p = p - 1
		else:
			ans = ans + 1
	print(ans)


import collections
import math
import sys
import itertools
import itertools

def sa(Type=int):
	return [Type(x) for x in input().split()]

def getOppositeBracket(ch):
	return '(' if ch == ')' else ')'

def solve(t):
	n = int(input())
	s = input()
	stack = collections.deque()
	for x in s:
		if len(stack) > 0:
			prev = stack.pop()
		else:
			prev = None
		if x != getOppositeBracket(prev):
			if prev is not None:
				stack.append(prev)
			stack.append(x)
	print(len(stack))
t = int(input())
for i in range(t):
	solve(i + 1)


def func(n):
	for i in range(n):
		k = int(input())
		s = input()
		l = []
		l2 = []
		counter = 0
		for i in s:
			if i == '(':
				l.append(i)
			elif l:
				if l.pop() != '(':
					l2.append(i)
					counter += 1
			else:
				l2.append(i)
				counter += 1
		print(counter)
n = int(input())
func(n)


for _ in range(int(input())):
	b = int(input())
	a = input()
	count = 0
	z = []
	for i in a:
		if i == '(':
			count += 1
		else:
			count -= 1
			if count < 0:
				z.append(count)
	if len(z) == 0:
		print(0)
	else:
		print(abs(min(z)))


def solve1(n, s):
	balance = 0
	moves = 0
	i = 0
	while i < n:
		if s[i] == '(':
			balance += 1
		else:
			balance += -1
		if balance < 0:
			s = s[0:i] + s[i + 1:] + s[i]
			moves += 1
			balance = 0
			i = 0
			continue
		i += 1
	return moves
testCases = int(input())
for case in range(testCases):
	n = int(input())
	s = input()
	x = solve1(n, s)
	print(x)


import io
import os
import sys
from collections import deque, defaultdict

def _input():
	x = sys.stdin.readline()
	x = x.replace('\r', '')
	x = x.replace('\n', '')
	return x
if 'STDINPUT' not in os.environ:
	input = _input
else:
	print('Standard input')

def solve():
	n = int(input())
	s = input()
	c = 0
	ans = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c += -1
		if c < 0:
			ans += 1
			c = 0
	print(ans)
test_cases = True
if test_cases:
	_q = int(input())
	for _ in range(_q):
		solve()
else:
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	count = 0
	r1 = 0
	r2 = 0
	for i in range(len(s)):
		if s[i] == '(':
			r1 += 1
		elif s[i] == ')':
			r2 += 1
		if r2 > r1:
			count += 1
			r2 -= 1
	print(count)


cases = int(input())
for cas in range(cases):
	n = int(input())
	s = input()
	count = 0
	moves = 0
	for i in range(len(s)):
		if s[i] == '(':
			count += 1
		if s[i] == ')':
			count -= 1
		if count < 0:
			moves += 1
			count += 1
	print(moves)


for _ in range(int(input())):
	n = int(input())
	arr = input()
	count = 0
	for k in range(n):
		if '()' in arr:
			arr = arr.replace('()', '', 1)
			count += 1
		else:
			break
	print((n - count * 2) // 2)


for test in range(int(input())):
	val = int(input())
	expressions = list((x for x in input()))
	stack = []
	for i in range(len(expressions)):
		if len(stack) == 0:
			stack.append(expressions[i])
		elif expressions[i] == ')':
			if stack[-1] == '(':
				stack.pop()
			else:
				stack.append(')')
		else:
			stack.append('(')
	print(len(stack) // 2)


from math import *
tests = int(input())
for t in range(tests):
	n = int(input())
	s = input()
	stack = []
	for i in range(len(s)):
		brac = s[i]
		if brac == ')' and len(stack) > 0 and (stack[-1] == '('):
			stack.pop()
		else:
			stack.append(brac)
	res = len(stack) // 2
	print(res)


from collections import deque
t = int(input())
for _ in range(t):
	n = input()
	s = input()
	deq = deque()
	for el in s:
		if el == '(':
			deq.append(el)
			continue
		if deq and deq[-1] == '(':
			deq.pop()
		else:
			deq.append(el)
	print(len(deq) // 2)


t = int(input())
while t:
	n = int(input())
	a = list(input())
	cb = ')'
	ob = '('
	track = 0
	m = 0
	for i in a:
		if i == cb:
			track -= 1
			if track < 0:
				m += 1
				track = 0
		else:
			track += 1
	print(m)
	t = t - 1


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

def L():
	return list(map(int, input().split()))

def In():
	return map(int, input().split())

def I():
	return int(input())
P = 1000000007

def main():
	for t in range(I()):
		n = I()
		arr = list(input())
		lis = []
		(n1, n2) = (0, 0)
		c = 0
		for i in range(n):
			if arr[i] == '(':
				n1 += 1
			else:
				n2 += 1
			if arr[i] == ')' and n1 + c < n2:
				c += 1
		print(c)
main()


for i in range(int(input())):
	n = input()
	s = input()
	table = {'(': 1, ')': -1}
	sum = count = 0
	for i in s:
		sum += table[i]
		if sum < 0:
			sum = 0
			count += 1
	print(count)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		l = []
		cl = 0
		for i in s:
			if i == '(':
				l.append(i)
			elif i == ')':
				if len(l) == 0:
					cl += 1
				else:
					l.pop()
		print(cl)
main()


t = int(input())
for _ in range(t):
	balance = 0
	(o, c) = (0, 0)
	answer = 0
	n = int(input())
	b = input()
	for i in b:
		if i == '(':
			o += 1
		elif i == ')':
			c += 1
		if c > o:
			answer += 1
			c = 0
			o = 0
	print(answer)


def solve():
	n = int(input())
	s = input()
	b = 0
	res = 0
	for i in range(n):
		if s[i] == '(':
			b -= 1
		else:
			b += 1
			if b > 0:
				b = 0
				res += 1
	print(res)

def main():
	q = int(input())
	for _ in range(q):
		solve()
main()


for t in range(int(input())):
	n = int(input())
	s = input()
	v = 0
	vmin = 0
	for c in s:
		if c == '(':
			v += 1
		else:
			v -= 1
			if v < vmin:
				vmin = v
	print(-vmin)


T = int(input())
for _ in range(T):
	N = int(input())
	brackets = input()
	open_b = []
	closed_b = []
	count = 0
	for i in brackets:
		if i == ')':
			if len(open_b) == 0 and len(closed_b) == 0:
				count += 1
			elif len(closed_b) > 0:
				closed_b.pop()
			else:
				open_b.append(i)
		elif len(open_b) > 0:
			open_b.pop()
		else:
			closed_b.append(i)
	print(count)


from collections import deque

def solve():
	n = int(input())
	q = deque([])
	ip = input()
	i = 0
	while ip[i] != '(':
		i += 1
	while i < n:
		if ip[i] == '(':
			q.append(ip[i])
		elif len(q):
			q.popleft()
		i += 1
	return len(q)
for _ in range(int(input())):
	print(solve())


T = int(input())
while T != 0:
	n = int(input())
	s = input()
	i = 0
	(nopen, nclose, ans) = (0, 0, 0)
	while i < n:
		if s[i] == '(':
			nopen += 1
		else:
			nclose += 1
			if nopen < nclose:
				ans += 1
				nclose -= 1
		i += 1
	print(ans)
	T -= 1


def swapCount(s):
	chars = s
	countLeft = 0
	countRight = 0
	swap = 0
	imbalance = 0
	for i in range(len(chars)):
		if chars[i] == '(':
			countLeft += 1
			if imbalance > 0:
				swap += imbalance
				imbalance -= 1
		elif chars[i] == ')':
			countRight += 1
			imbalance = countRight - countLeft
	return swap
t = int(input())
for u in range(t):
	n = int(input())
	s = input()
	m = 0
	e = 0
	for i in range(n):
		if s[i] == '(':
			m = m + 1
		elif s[i] == ')':
			if m == 0:
				e = e + 1
			else:
				m = m - 1
	print(e)


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
		elif input_format == 5:
			formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
		elif input_format == 6:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enum = enumerate

def solve():
	n = input(11)
	t = input(3)
	q = 0
	c = 0
	for i in t:
		if i == '(':
			q += 1
		else:
			q -= 1
		if q < 0:
			c += 1
			q = 0
	out(c)
	return
for i in range(input(11)):
	solve()


import sys
import math
import collections
import heapq
import queue
import itertools
import functools
import operator
import time
readline = sys.stdin.readline
IPS = lambda : readline().rstrip()
IP = lambda : int(readline().rstrip())
MP = lambda : map(int, readline().split())
LS = lambda : list(map(int, readline().split()))

def solve():
	for _ in range(IP()):
		n = IP()
		st = IPS()
		cnt = 0
		for elem in st:
			if elem == '(':
				cnt += 1
			else:
				cnt -= 1
			if cnt < 0:
				cnt = 0
		print(cnt)
solve()


testcase = int(input())
while testcase:
	testcase -= 1
	n = int(input())
	s = list(input())
	stack = []
	stack.append(s[0])
	for i in range(1, n):
		if s[i] == '(':
			stack.append(s[i])
		if s[i] == ')':
			if stack != [] and stack[-1] == '(':
				stack.pop()
			else:
				stack.append(s[i])
	print(len(stack) // 2)


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for ii in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	ans = 0
	for i in s:
		if i == '(':
			stack.append(1)
		if i == ')':
			if len(stack) == 0:
				ans += 1
			else:
				stack.pop()
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	d = 0
	maxi = 0
	for i in range(n):
		if s[i] == ')':
			d -= 1
			if d < maxi:
				maxi = d
		else:
			d += 1
	print(maxi * -1)


MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
from collections import *
for _ in range(ii()):
	n = ii()
	a = list(si())
	c = 0
	p = 0
	for i in range(0, n):
		if a[i] == '(':
			c = c + 1
		elif a[i] == ')':
			if c == 0:
				p = p + 1
			else:
				c = c - 1
	print(p)


for tt in range(int(input())):
	n = int(input())
	s = input()
	l = list(s)
	stack = []
	top = -1
	b = 0
	for i in l:
		if i == '(':
			stack.append(i)
			top += 1
		if i == ')':
			if top != -1:
				ele = stack.pop()
				top -= 1
				if ele == '(':
					b += 1
	print((n - 2 * b) // 2)


t = int(input())
for j in range(t):
	m = int(input())
	k = input()
	k = k[::-1]
	a = 0
	b = 0
	c = 0
	for j in k:
		if j == '(':
			a += 1
		if j == ')':
			b += 1
		if a > b:
			c += 1
			a -= 1
		elif a == b:
			a = 0
			b = 0
	print(c)


import os
is_dev = 'vscode' in os.environ
if is_dev:
	inF = open('in.txt', 'r')
	outF = open('out.txt', 'w')

def ins(r):
	return list(map(int, r.split(' ')))

def inputT():
	if is_dev:
		return inF.readline()[:-1]
	else:
		return input()

def printT(data=''):
	if is_dev:
		return outF.write(str(data) + '\n')
	else:
		return print(data)
for _ in range(int(inputT())):
	n = int(inputT())
	s = inputT()
	while '()' in s:
		s = s.replace('()', '')
	printT(len(s) >> 1)
if is_dev:
	outF.close()
	print(open('out.txt', 'r').read() == open('outactual.txt', 'r').read())


def MoveBrackets(n, s):
	total = 0
	moves = []
	for i in range(n):
		if s[i] == '(':
			total += 1
		else:
			total -= 1
		moves.append(total)
	return min(moves) * -1
Lista = []
total = int(input())
for i in range(total * 2):
	All = [str(i) for i in input().split()]
	Lista.append(All)
for j in range(0, len(Lista), 2):
	print(MoveBrackets(int(Lista[j][0]), Lista[j + 1][0]))


def c(s):
	fstack = 0
	move = 0
	l = []
	for i in range(len(s)):
		l.append(s[i])
	i = 0
	while i < len(l):
		if l[i] == '(':
			fstack += 1
		elif l[i] == ')' and fstack > 0:
			fstack -= 1
		elif l[i] == ')' and fstack == 0:
			move += 1
			del l[i]
			l.append(')')
			i -= 1
		i += 1
	return move
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	print(c(s))


t = int(input())
for _ in range(0, t):
	n = int(input())
	s = list(input())
	li = []
	ans = 0
	for x in s:
		if x == '(':
			li.append('(')
		elif len(li) > 0:
			li.pop()
	print(len(li))


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	p = 0
	x = [0]
	for i in range(n):
		if s[i] == '(':
			p += 1
		elif s[i] == ')':
			p -= 1
		if p < 0:
			x.append(abs(p))
	print(max(x))


import math
t = int(input())
for g in range(t):
	n = int(input())
	s = input()
	cnt = 0
	ans = 0
	for i in s:
		if i == ')':
			cnt -= 1
		else:
			cnt += 1
		if cnt < 0:
			cnt = 0
			ans += 1
	print(ans)


t = int(input())
for i in range(0, t):
	length = int(input())
	m = input()
	count1 = 0
	count2 = 0
	count = 0
	for i in range(0, length):
		if m[i] == '(':
			count1 = count1 + 1
		else:
			count2 = count2 + 1
		if count2 > count1:
			count = count + 1
			count2 = count2 - 1
	print(count)


b = []
t = int(input())
for _ in range(t):
	n = int(input())
	b.append(input())
for test in range(t):
	s = b[test]
	x = 0
	for i in range(len(s)):
		if s[i] == '(':
			x += 1
		else:
			x -= 1
		if x < 0:
			x = 0
	print(x)


for _ in range(int(input())):
	ans = 0
	bal = 0
	rango = int(input())
	brackets = input()
	for i in range(rango):
		if brackets[i] == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			ans += 1
			bal += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	string = input()
	balance = 0
	num_of_brackets = 0
	for char in string:
		if balance == -1:
			balance = 0
			num_of_brackets += 1
		if char == ')':
			balance -= 1
		if char == '(':
			balance += 1
	print(num_of_brackets)


it = lambda : list(map(int, input().strip().split()))

def solve():
	n = int(input())
	s = input().strip()
	ans = 0
	cur = 0
	for i in range(n):
		if s[i] == ')':
			cur -= 1
		else:
			cur += 1
		if cur < 0:
			ans += 1
			cur = 0
	print(ans)
T = int(input())
for _ in range(T):
	solve()


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	c = 0
	x = []
	j = 0
	while j < len(s):
		if s[j] == '(':
			x.append(s[j])
			j += 1
		elif s[j] == ')':
			if len(x) > 0 and x[-1] == '(':
				x.pop()
				j += 1
			else:
				a = s.pop(j)
				s.append(a)
				c += 1
	print(c)


for _ in range(int(input())):
	size = int(input())
	string = input()
	stack = []
	for s in string:
		if s == '(':
			stack.append(s)
		elif len(stack) != 0:
			stack.pop()
	print(len(stack))


num_exa = int(input())
for num in range(num_exa):
	len_string = int(input())
	b_string = input()
	num_open = 0
	num_close = 0
	num_atEnd = 0
	for i in range(len_string):
		if b_string[i] == '(':
			num_open = num_open + 1
		elif b_string[i] == ')':
			num_close = num_close + 1
		if num_close > num_open + num_atEnd:
			num_atEnd = num_atEnd + 1
	print(num_atEnd)


t = int(input())
for tt in range(t):
	n = int(input())
	s = input()
	a = []
	for i in range(len(s)):
		if s[i] == '(':
			a.append(1)
		else:
			a.append(-1)
	for i in range(n):
		if a[i] == -1 or a[i] == 0:
			continue
		bhul = True
		for j in range(i, n):
			if a[j] == -1:
				a[i] = 0
				a[j] = 0
				bhul = False
				break
		if bhul:
			break
	print(a.count(1))


t = int(input())
for z in range(t):
	n = int(input())
	s = input()
	d = []
	for i in range(n):
		if s[i] == '(':
			d.append(s[i])
		elif not d:
			d.append(s[i])
		else:
			r = d.pop()
			if r != '(':
				d.append(r)
				d.append(s[i])
	print(len(d) // 2)


t = int(input())
for test in range(t):
	x = int(input())
	s = input()
	c = 0
	m = 0
	for i in range(len(s)):
		if s[i] == '(':
			c = c + 1
		else:
			c = c - 1
		if c < 0 and c < m:
			m = m - 1
	print(abs(m))


try:
	t = int(input())
	while t:
		input()
		s = input()
		stc = []
		ans = 0
		for c in s:
			if c == ')':
				if len(stc) == 0:
					ans += 1
				elif len(stc) > 0:
					if len(stc) > 0 and stc[-1] == '(':
						stc.pop()
			else:
				stc.append('(')
		print(ans)
		t -= 1
except:
	pass


for _ in range(int(input().strip())):
	n = int(input().strip())
	st = input()
	(ans, bal) = (0, 0)
	for i in range(len(st)):
		if st[i] == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ob = 0
	cb = 0
	c = 0
	for i in s:
		if i == '(':
			ob = ob + 1
		elif i == ')' and ob <= cb:
			cb = cb + 1
			c = c + cb - ob
			ob = 0
			cb = 0
		else:
			cb = cb + 1
	print(c)


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
for _ in range(inp()):
	n = inp()
	s = input().strip()
	stack = []
	for i in range(n):
		stack.append(s[i])
		if len(stack) >= 2 and stack[-2:] == ['(', ')']:
			stack.pop()
			stack.pop()
	print(len(stack) // 2)


t = int(input())
for i in range(t):
	k = int(input())
	s = input()
	s = s[::-1]
	o = 0
	c = 0
	m = 0
	for i in s:
		if i == '(':
			o += 1
		if i == ')':
			c += 1
		if o > c:
			m += 1
			o -= 1
		elif o == c:
			o = 0
			c = 0
	print(m)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(lt, rt) = (0, 0)
	res = 0
	for i in s:
		if i == '(':
			lt += 1
		else:
			rt += 1
		if lt >= rt:
			continue
		else:
			res += 1
			lt += 1
	print(res)


t = int(input())
for i in range(t):
	n = int(input())
	k = input()
	r = []
	for j in k:
		if j == '(':
			r.append(j)
		elif len(r) > 0:
			if r[-1] == '(':
				r.pop()
			else:
				r.append(j)
		else:
			r.append(j)
	print(len(r) // 2)


t = int(input())
for q in range(t):
	_ = input()
	brackets = input()
	ans = 0
	x = 0
	for i in brackets:
		if i == '(':
			x += 1
		else:
			x -= 1
			if x < 0:
				ans += 1
				x = 0
	print(ans)


import math
import datetime
import collections
import statistics
import itertools

def is_prime(num):
	for i in range(2, int(math.sqrt(num)) + 1):
		if num % i == 0:
			return False
	return True

def input_list():
	ll = list(map(int, input().split(' ')))
	return ll
tc = int(input())
for _ in range(tc):
	n = int(input())
	s = input()
	m = 1000000
	ss = 0
	for i in s:
		if i == '(':
			ss += 1
		elif i == ')':
			ss -= 1
		m = min(m, ss)
	print(-1 * m)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	o = 0
	closed = 0
	for c in s:
		if c == '(':
			o += 1
			o = max(o, 1)
		elif not o:
			closed += 1
		else:
			o -= 1
	print(closed)


def converter(s, n):
	pilha = []
	for c in s:
		if c == '(' or len(pilha) == 0:
			pilha.append(c)
		elif pilha[-1] == '(' and c == ')':
			pilha.pop()
		else:
			pilha.append(c)
	return len(pilha) // 2
t = int(input())
for caso in range(t):
	n = int(input())
	s = input()
	print(converter(s, n))


for _ in range(int(input())):
	a = int(input())
	n = input()
	while n.find('()') != -1:
		n = ''.join(n.split('()'))
	print(len(n) // 2)


for _ in range(int(input())):
	n = int(input())
	brac = input()
	st = []
	count = 0
	for i in brac:
		if i == '(':
			st.append(i)
		elif len(st) == 0:
			count += 1
		else:
			st.pop()
	print(count)


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	s = insr()
	q = 0
	w = 0
	for i in range(len(s)):
		if s[i] == ')':
			q = q + 1
		else:
			q = q - 1
		w = max(q, w)
	print(w)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
T = inp()
tests = []
for i in range(T):
	inp()
	tests.append(insr())
for test in tests:
	open = 0
	bad = 0
	for c in test:
		if c == '(':
			open += 1
		elif open > 0:
			open -= 1
		else:
			bad += 1
	print(bad)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip()
	stack = []
	for i in s:
		if len(stack) == 0:
			stack.append(i)
			continue
		if stack[-1] == '(' and i == ')':
			stack.pop()
		else:
			stack.append(i)
	print(len(stack) // 2)


def getMinSwap(l, s):
	count = 0
	lp = 0
	for i in s:
		if i == ')':
			if lp == 0:
				count += 1
			else:
				lp -= 1
		if i == '(':
			lp += 1
	return count

def rmain():
	q = int(input())
	for _ in range(q):
		(l, s) = (int(input()), input())
		print(getMinSwap(l, s))
rmain()


n = int(input())

def solve():
	length = int(input())
	data = list(input())
	stack = []
	for i in data:
		if len(stack) == 0:
			stack.append(i)
		else:
			last = stack[len(stack) - 1]
			if last == '(' and i == ')':
				stack.pop(len(stack) - 1)
			else:
				stack.append(i)
	print(len(stack) // 2)
for i in range(n):
	solve()


def is_pair(bracket0, bracket1):
	return (bracket0, bracket1) == ('(', ')')

def regular_brackets(string):
	num_of_moves = 0
	brackets_list = []
	for bracket in string:
		if bracket == '(':
			brackets_list.append(bracket)
		elif len(brackets_list):
			brackets_list.pop()
		else:
			num_of_moves += 1
	return num_of_moves
test_cases = int(input())
while test_cases:
	input()
	print(regular_brackets(input()))
	test_cases -= 1


import math
import os
import random
import re
import sys
import collections

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n and i <= 3:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return factors

def solve():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		while '()' in s:
			s = s.replace('()', '')
		if s == '':
			print(0)
		else:
			print(s.count('('))
solve()


t = int(input())
for case in range(t):
	n = int(input())
	s = list(input())
	moves = 0
	while True:
		streak = 0
		for index in range(n):
			if s[index] == '(':
				streak += 1
			else:
				streak -= 1
			if streak < 0:
				s.append(s.pop(index))
				moves += 1
				break
		if index == n - 1:
			break
	print(moves)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt = 0
	mn = 0
	for i in range(n):
		if s[i] == ')':
			cnt += 1
		else:
			cnt -= 1
		mn = max(mn, cnt)
	print(mn)


for _ in range(int(input())):
	n = int(input())
	s = input()
	arr = []
	for i in s:
		if i == '(':
			arr.append(i)
		elif len(arr) >= 1:
			if arr[-1] == '(':
				del arr[-1]
			else:
				arr.append(i)
		else:
			arr.append(i)
	n = len(arr)
	print(int(n / 2))


tc = int(input())
c = 1
while c <= tc:
	n = int(input())
	lst = [str(j) for j in input().split()]
	st = ''.join(lst)
	l = '('
	r = ')'
	full = 0
	count = 0
	for i in range(len(st)):
		if st[i] == l:
			full += 1
		else:
			full -= 1
			if full < 0:
				full = 0
				count += 1
	print(count)
	c += 1


def solve(s):
	l = 0
	ans = 0
	for c in s:
		if c == '(':
			l += 1
		if c == ')':
			if l == 0:
				ans += 1
			else:
				l -= 1
	return (ans + l) // 2
t = int(input())
for _ in range(t):
	input()
	print(solve(input()))


t = int(input())
while t:
	n = int(input())
	s = input()
	matched = 0
	cnt = 0
	for i in range(n):
		if s[i] == '(':
			cnt += 1
		elif cnt > 0:
			cnt -= 1
			matched += 1
	print(n // 2 - matched)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	t = n
	i = 0
	moves = 0
	(l, r) = (0, 0)
	while i < t:
		if s[i] == '(':
			l += 1
		else:
			r += 1
		i += 1
		if l < r:
			moves += 1
			r -= 1
	print(moves)


for i in range(int(input())):
	n = int(input())
	string = input()
	stack = 0
	ans = 0
	for char in string:
		if char == '(':
			stack += 1
		else:
			stack -= 1
		ans = min(stack, ans)
	print(abs(ans))


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = []
	for i in range(n):
		if s[i] == '(':
			l.append('(')
		elif s[i] == ')' and '(' in l:
			l.remove('(')
		else:
			l.append(')')
	print(len(l) // 2)


t = int(input())
outputs = []
for i in range(t):
	n = int(input())
	s = input()
	output = [n, s]
	outputs.append(output)

def task(output):
	n = output[0]
	s = output[1]
	amount_left = 0
	result = 0
	for symb in s:
		if symb == '(':
			amount_left += 1
		elif amount_left > 0:
			amount_left -= 1
		else:
			result += 1
	return result
for output in outputs:
	print(task(output))


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	o = 0
	c = 0
	count = 0
	loop = True
	while loop == True:
		for (i, pos) in enumerate(s):
			if pos == '(':
				o += 1
			else:
				c += 1
			if c > o:
				index = s.find(')')
				s = s[:index] + s[index + 1:] + ')'
				count += 1
				o = 0
				c = 0
				break
			if i == len(s) - 1:
				print(count)
				loop = False


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	c = 0
	ans = 0
	mn = 0
	for i in range(n):
		if s[i] == ')':
			c -= 1
		else:
			c += 1
		if c < mn:
			mn = c
			ans += 1
	print(ans)


t = int(input())

def isitnotgood(s, mode):
	counter = 1
	notFound = True
	if mode == 'forward':
		j = 0
		while j < len(s):
			if s[j] == '(':
				counter += 1
			else:
				counter -= 1
			if counter == 0:
				notFound = False
			j += 1
	else:
		j = len(s) - 1
		while j >= 0:
			if s[j] == ')':
				counter += 1
			else:
				counter -= 1
			if counter == 0:
				notFound = False
			j -= 1
	return notFound
for _ in range(t):
	n = int(input())
	s = input()
	a = []
	i = 0
	notc = 0
	while i < n:
		if s[i] == '(':
			if isitnotgood(s[i + 1:], mode='forward'):
				notc += 1
		elif isitnotgood(s[:i], mode='backward'):
			notc += 1
		i += 1
	print(notc // 2)


from sys import stdin
for _ in range(int(input())):
	n = int(input())
	s = input()
	x = s.find('(')
	st = [s[x]]
	c = x
	for i in range(x + 1, n):
		if st:
			if s[i] == ')':
				st.pop()
			else:
				st.append(s[i])
		elif s[i] == '(':
			st.append(s[i])
		else:
			c += 1
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	scoremin = 0
	current = 0
	for i in range(n):
		if s[i] == '(':
			current += 1
		else:
			current -= 1
		scoremin = min(scoremin, current)
	print(-scoremin)


import math
import time
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	val = 0
	ans = 0
	for i in s:
		if i == '(':
			val += 1
		else:
			val -= 1
		if val < 0:
			val = 0
			ans += 1
	ans += val
	print(ans // 2)


t = int(input())
for i in range(t):
	n = int(input())
	st = []
	s = str(input())
	for j in s:
		if j == '(':
			st.append(j)
		elif len(st) != 0 and st[-1] == '(':
			st.pop()
		else:
			st.append(j)
	print(len(st) // 2)


t = int(input())
for ti in range(t):
	n = int(input())
	s = input()
	ulp = 0
	urp = 0
	for c in s:
		if c == '(':
			ulp += 1
		elif ulp:
			ulp -= 1
		else:
			urp += 1
	print(min(ulp, urp))


n = int(input())
for i in range(n):
	num = int(input())
	string = input()
	openpar = 0
	leftpar = 0
	for i in string:
		if i == '(':
			openpar += 1
		elif i == ')' and openpar != 0:
			openpar -= 1
		elif i == ')' and openpar == 0:
			leftpar += 1
	print(leftpar)


def solve(n, ar):
	cnt = 0
	res = 0
	for i in range(n):
		if ar[i] == '(':
			cnt += 1
			continue
		elif cnt == 0:
			res += 1
		else:
			cnt -= 1
	print(res)
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(input())
	solve(n, ar)


import sys
t = int(input())
for x in range(t):
	num_brackets = int(input())
	brackets = str(input())
	arr = []
	for i in brackets:
		arr.append(i)
	moves = 0
	bracket_tot = 0
	for char in arr:
		if char == '(':
			bracket_tot += 1
		else:
			bracket_tot -= 1
			if bracket_tot < 0:
				moves += 1
				bracket_tot = 0
	print(moves)


def proc_set():
	current = 0
	_min = 0
	_ = int(input())
	s = input()
	for x in s:
		if x == '(':
			current += 1
		else:
			current -= 1
			_min = min(_min, current)
	print(-_min)
n_sets = int(input())
for i in range(n_sets):
	proc_set()


for t in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	var = 0
	for i in range(len(s)):
		if s[i] == '(':
			var += 1
		else:
			var -= 1
		if var < 0:
			count += 1
			var = 0
	print(count)


n = int(input())
for _ in range(n):
	b = int(input())
	s = [1 if i == ')' else -1 for i in input()]
	su = s[0]
	max_ = su
	for i in range(1, len(s)):
		su += s[i]
		if su > max_:
			max_ = su
	print(max_)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	open = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			open += 1
		elif open == 0:
			ans += 1
		else:
			open -= 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	while s.find('()') != -1:
		s = s.replace('()', '')
	print(len(s) // 2)


x = int(input())
for _ in range(x):
	n = int(input())
	brack = input()
	i = 0
	while '()' in brack:
		brack = brack.replace('()', '', 1)
	print(len(brack) // 2)


t = int(input())
for i in range(0, t):
	n = int(input())
	s = str(input())
	L = []
	M = []
	for i in range(0, n):
		if s[i] == '(':
			L.append(s[i])
		else:
			M.append(s[i])
			if len(L) > 0:
				L.pop()
	print(len(L))


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	N = int(input())
	s = input()
	extra = 0
	A = []
	for i in range(N):
		if s[i] == '(':
			A.append(s[i])
		elif len(A) == 0:
			extra += 1
		elif A[-1] == '(':
			A.pop()
	print(extra)


t = int(input())
for z in range(t):
	n = int(input())
	s = str(input())
	st = []
	ans = 0
	for i in s:
		if i == '(':
			st.append(i)
		elif i == ')' and len(st) > 0:
			st.pop()
		elif i == ')' and len(st) == 0:
			ans += 1
	ans += len(st)
	print(int(ans / 2))


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
import io, os
input = sys.stdin.readline
from bisect import *
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().strip().split()))
rls = lambda : list(map(str, input().split()))
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = input().strip()
	s = []
	for i in range(0, len(a)):
		s.append(a[i])
		if len(s) > 1 and s[-2] == '(' and (s[-1] == ')'):
			s.pop()
			s.pop()
	if len(s) > 1 and s[-2] == '(' and (s[-1] == ')'):
		s.pop()
		s.pop()
	print(len(s) // 2)


t = int(input())
list = []
for i in range(t):
	n = input()
	bracket_sequence = input()
	list.append([n, bracket_sequence])
for sequence in list:
	n = sequence[0]
	brackets = sequence[1]
	moves = 0
	count = 0
	for bracket in brackets:
		if bracket == '(':
			count += 1
		elif bracket == ')':
			count -= 1
		if count < 0:
			moves += 1
			count = 0
	print(moves)


t = int(input())
for _ in range(t):
	n = int(input())
	k = input()
	temp = []
	c = 0
	for i in k:
		if i == '(':
			temp.append('(')
		elif temp != [] and i == ')' and (temp[-1] == '('):
			temp.pop()
		else:
			c += 1
	print(c)


def unbalancing(s):
	x = 0
	retvalue = 0
	for c in s:
		if c == '(':
			x += 1
		else:
			x -= 1
		retvalue = min(retvalue, x)
	return retvalue
for _ in range(int(input())):
	n = int(input())
	s = input()
	print(-unbalancing(s))


import sys
for _ in range(int(input())):
	n = int(input())
	s = input()
	(sums, ans) = (0, 0)
	for c in s:
		if c == '(':
			sums -= 1
		else:
			sums += 1
		ans = max(ans, sums)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	m = []
	mc = []
	for i in range(n):
		if s[i] == '(':
			m.append(s[i])
		elif len(m) == 0:
			mc.append(s[i])
		else:
			m.remove('(')
	print(len(mc))


T = int(input())
for test in range(T):
	n = int(input())
	s = input()
	ans = 0
	(ok, rev) = (0, 0)
	for el in s:
		if el == '(':
			ok += 1
		else:
			rev += 1
		if rev > ok:
			ans += 1
			rev -= 1
	print(ans)


for i in range(int(input())):
	n = int(input())
	s = list(input())
	(x, ans) = (0, 0)
	for j in range(n):
		if x == 0 and s[j] == ')':
			ans = ans + 1
		elif s[j] == '(':
			x = x + 1
		elif s[j] == ')':
			x = x - 1
	print(ans)


for i in range(int(input())):
	z = int(input())
	s = input()
	l = 0
	ans = 0
	for i in s:
		if i == '(':
			l += 1
		elif l > 0:
			l -= 1
		else:
			ans += 1
	print(ans)


from sys import stdin

def main():
	input = lambda : stdin.readline()[:-1]
	T = int(input())
	for _ in [0] * T:
		N = int(input())
		S = input()
		(ans, n) = (0, 0)
		for s in S:
			if s == '(':
				n += 1
			else:
				n -= 1
			ans = min(ans, n)
		print(abs(ans))
main()


for _ in range(int(input())):
	n = int(input())
	b = input()
	o = 0
	c = 0
	res = 0
	for each in b:
		if each == '(':
			o += 1
		else:
			c += 1
		if c > o:
			c -= 1
			res += 1
	print(res)


for t in range(int(input())):
	n = int(input())
	s = input()
	count = 0
	minm = 0
	for c in s:
		if c == '(':
			count += 1
		elif c == ')':
			count -= 1
			if count < minm:
				minm = count
	print(abs(minm))


for _ in range(int(input())):
	n = int(input())
	s = input()
	m = 0
	cnt = 0
	for i in range(n):
		if s[i] == '(':
			cnt += 1
		if s[i] == ')':
			cnt -= 1
			m = min(m, cnt)
	print(abs(m))


t = int(input())
for x in range(t):
	n = int(input())
	s = input()
	moves = 0
	st = []
	for ch in s:
		if len(st) == 0:
			if ch == ')':
				moves += 1
			st.append(ch)
		elif st[-1] == ')' and ch == ')':
			st.append(ch)
			moves += 1
		elif ch == '(':
			st.append(ch)
		elif st[-1] != ch:
			st.pop()
	if len(st) == 0:
		moves += len(st) / 2
	print(int(moves))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	n = int(ri())
	s = ri()
	cnt = 0
	minn = 0
	for i in s:
		if i == '(':
			cnt += 1
		if i == ')':
			cnt -= 1
		minn = min(minn, cnt)
	print(abs(minn))


T = int(input())
for tc in range(T):
	l = input()
	sq = list(input())
	fq = 0
	fp = 0
	for i in sq:
		if fq == 0 and i == ')':
			fp += 1
		elif i == '(':
			fq += 1
		elif i == ')':
			fq -= 1
	print(fp)


tests = int(input())
for n in range(tests):
	leng = int(input())
	s = str(input())
	tries = 0
	while True:
		tracker = 0
		last_par = 0
		for m in range(leng):
			if s[m] == '(':
				tracker += 1
				last_par = m
			else:
				tracker -= 1
			if tracker < 0:
				tries += 1
				s = s[:m] + s[m + 1:]
				s = s + ')'
				break
		if tracker > 0:
			tries += 1
			s = s[:last_par] + s[last_par + 1:]
			s = '(' + s
		elif tracker == 0:
			print(tries)
			break


for _ in range(int(input())):
	n = int(input())
	string = input()
	op = 0
	moves = 0
	for i in string:
		if i == '(':
			op += 1
		elif op == 0:
			moves += 1
		else:
			op -= 1
	print(moves)


def read_list():
	return list(map(int, input().strip().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))

def judge_3(n):
	tmp = 0
	for c in str(n):
		tmp += int(c)
	return tmp % 3 == 0
N = int(input())
for _ in range(N):
	n = input()
	s = input()
	tmp = 0
	res = 0
	for c in s:
		if c == ')':
			tmp += 1
			res = max(res, tmp)
		else:
			tmp -= 1
	print(res)


def fun(n, st):
	s = []
	r = 0
	for i in range(n):
		if len(s) == 0:
			s.append(st[i])
		elif st[i] == ')' and s[-1] == '(':
			s.pop()
		else:
			s.append(st[i])
	print(len(s) // 2)
for i in range(int(input())):
	n = int(input())
	st = input()
	fun(n, st)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input().rstrip()
	count = 0
	neg = 0
	pos = 0
	diff = 0
	for i in range(n):
		diff = pos - neg
		if s[i] == '(':
			pos += 1
		else:
			neg += 1
		if neg > pos:
			count += 1
			neg = 0
			pos = 0
	print(count)


for _ in range(int(input())):
	n = int(input())
	paren = input()
	s = []
	cout = 0
	for i in paren:
		if i == '(':
			s.append(i)
		elif len(s) == 0:
			cout += 1
		elif s[-1] != '(':
			cout += 1
		else:
			s.pop()
	print(cout)


t = int(input())
while t:
	ans = k = 0
	n = int(input())
	s = input()
	for i in s:
		if i == '(':
			k += 1
		else:
			k -= 1
		if k < 0:
			ans += 1
			k = 0
	print(ans)
	t = t - 1


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	s = input()
	stack = []
	closing = []
	for i in range(n):
		if s[i] == '(':
			stack.append(i)
		elif len(stack) == 0:
			closing.append(i)
		else:
			X = stack.pop()
	print(len(stack))


import sys, math, cmath, time, collections
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace
from math import ceil, floor, log, log2, sqrt, gcd, factorial, pow, pi
from bisect import bisect_left, bisect_right
start_time = time.time()

def solve(s, n):
	cnt = 0
	open = ['(']
	closed = [')']
	stack = []
	for i in range(n):
		if s[i] in open:
			stack.append(s[i])
		elif s[i] in closed and stack:
			stack.pop()
		else:
			cnt += 1
	print(cnt)

def main():
	n = int(input())
	s = input()
	solve(s, n)
LOCAL = False
if LOCAL:
	sys.stdin = open('data.in', 'r')
	sys.stdout = open('data.out', 'w')
testcases = int(input())
for i in range(testcases):
	main()
if LOCAL:
	print(f'Time Elapsed: {time.time() - start_time} seconds')
	sys.stdout.close()


for k in range(int(input())):
	x = input()
	a = input()
	c = 0
	while True:
		try:
			i = a.index('()')
			a = a[:i] + a[i + 2:]
		except:
			c += a.count('(')
			break
	print(c)


def readintlst():
	return list(map(int, input().split(' ')))

def readn():
	return int(input())
import math
for _ in range(readn()):
	n = readn()
	s = input()
	stack = []
	op = 0
	cl = 0
	for c in s:
		if c == '(':
			op += 1
		elif c == ')':
			if op > 0:
				op -= 1
			else:
				cl += 1
	print((op + cl) // 2)


import math
import sys
import os
for _ in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	print(len(s) // 2)


from sys import stdin
for case in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	diff = 0
	maxDiff = 0
	for x in s:
		if x == '(':
			diff += 1
		else:
			diff -= 1
		maxDiff = min(diff, maxDiff)
	print(-maxDiff)


testn = int(input())
for i in range(testn):
	length = input()
	brackets = input()
	count = 0
	min_count = 0
	for b in brackets:
		if b == ')':
			count -= 1
		else:
			count += 1
		min_count = min(min_count, count)
	print(abs(min_count))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().strip().split(' ')))

def solve():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		a = 0
		for i in s:
			if i == '(':
				a += 1
			elif a > 0:
				a -= 1
		print(a)
solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = 0
	c = 0
	for s_i in s:
		if s_i == '(':
			c += 1
		else:
			c -= 1
			ans = max(ans, -c)
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(b, c) = (0, 0)
	for j in range(len(s)):
		if s[j] == ')':
			if b == 0:
				c += 1
			else:
				b -= 1
		if s[j] == '(':
			b += 1
	print(c)


n = int(input())
l = []
while n:
	m = int(input())
	s = input()
	count = 0
	res = 0
	for i in s:
		if i == '(':
			count = count + 1
		else:
			count = count - 1
		res = min(res, count)
	l.append(-res)
	n = n - 1
for j in l:
	print(j)


for i in range(int(input())):
	n = int(input())
	s = input()
	left = right = 0
	for j in s:
		if j == '(':
			left += 1
		elif left:
			left -= 1
		else:
			right += 1
	print((left + right) // 2)


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	n = int(input())
	s = input()
	st = []
	ans = 0
	for i in s:
		if i == '(':
			st.append(i)
		elif len(st):
			st.pop()
		else:
			ans += 1
	if st:
		ans += len(st)
	print(ans // 2)


from sys import stdin
n = int(stdin.readline())
for i in range(n):
	c = int(stdin.readline())
	s = input()
	total = 0
	move = 0
	for i in s:
		if i == '(':
			total += 1
		if i == ')':
			total -= 1
			if total < 0:
				move += 1
				total = 0
	print(move)


def f():
	n = int(input())
	s = input()
	bal = 0
	hod = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
		if bal < 0:
			hod += 1
			bal += 1
	print(hod)
t = int(input())
for i in range(t):
	f()


def sol(lis):
	stack = []
	for i in range(len(lis)):
		if stack == []:
			stack.append(lis[i])
		elif stack[-1] == '(' and lis[i] == ')':
			stack.pop()
		else:
			stack.append(lis[i])
	print(len(stack) // 2)
k = int(input())
for i in range(k):
	input()
	s = input()
	sol(s)


import sys
t = int(sys.stdin.readline().strip())
while t:
	n = int(sys.stdin.readline().strip())
	s = sys.stdin.readline().strip()
	stack = []
	for e in s:
		if not stack:
			stack.append(e)
		elif stack[-1] == '(' and e == ')':
			stack.pop()
		else:
			stack.append(e)
	print(len(stack) // 2)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	c = 0
	m = 0
	for i in range(len(s)):
		if s[i] == ')' and c == 0:
			m = m + 1
		elif s[i] == '(':
			c = c + 1
		elif s[i] == ')' and c > 0:
			c = c - 1
	print(m)


def solution1():
	for tangocharlie in range(int(input())):
		(xx, yy, nn) = map(int, input().split())
		p = nn // xx
		k = p * xx + yy
		while k > nn:
			p -= 1
			k = p * xx + yy
		print(k)

def solution2():
	for tangocharlie in range(int(input())):
		nnn = int(input())
		apple = 5
		banana = 10
		orange = apple + banana
		answer = 0
		while nnn > 1:
			if nnn % 6 == 0:
				answer += 1
				nnn = nnn // 6
			elif nnn % 3 == 0 and nnn % 2 != 0:
				answer += 1
				nnn *= 2
			else:
				answer = -1
				break
		print(answer)

def solution3():
	for tangocharlie in range(int(input())):
		number = int(input())
		sunlight = list(input())
		opnn = wrong = 0
		for i in sunlight:
			if i == '(':
				opnn += 1
			else:
				opnn -= 1
			if opnn < 0:
				wrong += 1
				opnn = 0
		print(wrong)

def solution4():
	for tangocharlie in range(int(input())):
		(n, k) = map(int, input().split())
		abra_ka_dabra = sorted(list(map(int, input().split())))
		abra_ka_dabra1 = []
		for i in abra_ka_dabra:
			if i % k != 0:
				abra_ka_dabra1.append(k - i % k)
		if len(abra_ka_dabra1) == 0:
			print(0)
			continue
		abra_ka_dabra1.sort()
		ans = abra_ka_dabra1[0]
		curr = abra_ka_dabra1[0]
		for i in range(1, len(abra_ka_dabra1)):
			if abra_ka_dabra1[i] != abra_ka_dabra1[i - 1]:
				curr = abra_ka_dabra1[i]
			else:
				curr += k
			ans = max(ans, curr)
		print(ans + 1)
solution3()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(open, close) = (0, 0)
	for i in range(n):
		if s[i] == '(':
			open += 1
		if s[i] == ')':
			close += 1
		if close > open:
			close -= 1
	print(open - close)


from math import *
from copy import *
from string import *
from random import *
from sys import stdin, stdout
from sys import maxsize
from operator import *
from itertools import *
from collections import Counter
import math
import math
import time
from queue import Queue

def seive(n):
	l = [True]
	l = l * (n + 1)
	for i in range(2, int(sqrt(n)) + 1):
		if l[i] == True:
			val = i * i
			while val < len(l):
				l[val] = False
				val += i
	prime = []
	for i in range(2, len(l)):
		if l[i] == True:
			prime.append(i)
	return prime

def dp(l, i, n, val, ans):
	if i >= n or val < 0:
		return 1000000
	elif val == 0:
		return 0
	else:
		if ans[i] == 1000000:
			ans[i] = min(min(1 + dp(l, i + 1, n, val - l[i], ans), 1 + dp(l, i, n, val - l[i], ans)), dp(l, i + 1, n, val, ans))
		return ans[i]
from queue import Queue

def factors(n):
	l = []
	for i in range(1, int(sqrt(n)) + 1):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def check1(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v -= 1

def check2(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v += 1

def up(n):
	j = n - 1
	while j > 0:
		if n % j == 0:
			break
		j -= 1
	return j
t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	l = []
	for i in range(len(s)):
		if len(l) == 0:
			l.append(s[i:i + 1])
		elif l[len(l) - 1] == '(':
			if s[i:i + 1] == ')':
				l.pop()
			else:
				l.append('(')
		else:
			l.append(s[i:i + 1])
	print(len(l) // 2)


t = int(input())
for i in range(t):
	p = int(input())
	y = list(input())
	j = 0
	c = 0
	s = 0
	while j < p:
		if y[j] == '(':
			j += 1
			c += 1
		else:
			c -= 1
			if c < 0:
				y.pop(j)
				y.append(')')
				s += 1
				c += 1
			else:
				j += 1
	print(s)


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	c = 0
	i = 0
	while i < n:
		if s[i] == '(':
			stack.append(s[i])
			i += 1
		elif not stack:
			s = s[:i] + s[i + 1:] + s[i]
			c += 1
		else:
			stack.pop()
			i += 1
	print(c)


import sys
input = sys.stdin.readline

def solve(n, S):
	minS = n + 1
	cnt = 0
	for s in S:
		if s == '(':
			cnt += 1
		else:
			cnt -= 1
			minS = min(minS, cnt)
	return -minS

def main():
	mod = 1000000007
	inv = lambda x: pow(x, mod - 2, mod)
	t = int(input())
	for _ in range(t):
		n = int(input())
		S = input().strip()
		ans = solve(n, S)
		sys.stdout.write(str(ans) + '\n')
main()


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	s = SI()
	count = 0
	ans = 0
	for i in s:
		if i == ')':
			if count > 0:
				count -= 1
				ans += 1
		else:
			count += 1
	print((n - 2 * ans) // 2)


n = int(input())
for i in range(n):
	n1 = int(input())
	param = 0
	ans = 0
	seq = input()
	A = [i1 for i1 in seq]
	for i2 in A:
		if i2 == '(':
			param += 1
		else:
			param -= 1
		if param < 0:
			ans += 1
			param = 0
			A.reverse()
			A.remove('(')
			A.reverse()
	print(ans)


for i in range(int(input())):
	n = int(input())
	s = input()
	s = s.replace('()', '')
	while s.count('()') > 0:
		s = s.replace('()', '')
	print(s.count('('))


for i in range(int(input())):
	n = int(input())
	s = input()
	while '()' in s:
		s = ''.join(s.split('()'))
	print(int(len(s) / 2))


for jn in range(int(input())):
	c = int(input())
	a = input()
	for i in range(c):
		if '()' in a:
			a = a.replace('()', '')
		else:
			break
	print(len(a) // 2)


for _ in range(int(input())):
	n = int(input())
	s = input()
	imbalance = 0
	stack = []
	for c in s:
		if c == '(':
			stack.append(c)
		elif stack:
			stack.pop()
		else:
			imbalance += 1
	print(imbalance)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	total = 0
	bracket = 0
	for i in range(n):
		if s[i] == '(':
			if bracket <= 0:
				bracket = 1
			else:
				bracket += 1
		else:
			bracket -= 1
			if bracket < 0:
				total += 1
	if bracket > 0:
		total += bracket
	print((total + 2 - 1) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	staker = []
	count = 0
	for j in range(n):
		if s[j] == ')' and len(staker) == 0:
			count += 1
		elif s[j] == '(':
			staker.append(1)
		elif s[j] == ')':
			staker.pop()
	print(count)


import sys
import random
from math import *

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def finput():
	return float(input())

def tinput():
	return input().split()

def linput():
	return list(input())

def rinput():
	return map(int, tinput())

def fiinput():
	return map(float, tinput())

def rlinput():
	return list(map(int, input().split()))

def trinput():
	return tuple(rinput())

def srlinput():
	return sorted(list(map(int, input().split())))

def NOYES(fl):
	if fl:
		print('NO')
	else:
		print('YES')

def YESNO(fl):
	if fl:
		print('YES')
	else:
		print('NO')

def main():
	n = iinput()
	s = linput()
	m = b = 0
	for i in s:
		b += 1 if i == '(' else -1
		m = min(m, b)
	print(0 if m >= 0 else abs(m))
for inytd in range(iinput()):
	main()


for t in range(int(input())):
	n = int(input())
	s = input()
	ls = []
	for c in s:
		if c == '(':
			ls += [1]
		if c == ')':
			if ls and ls[-1] == 1:
				ls = ls[:-1]
			else:
				ls += [-1]
	print(len(ls) // 2)


n = int(input())
for _ in range(n):
	fu = input()
	s = input()
	Count = 0
	while '()' in s:
		Count += s.count('()')
		s = s.replace('()', '')
	print(int(len(s) / 2))


T = int(input())

def main():
	my_dict = {'(': True, ')': False}
	n = int(input())
	s = input()
	stack = []
	count = 0
	pointer = 0
	while pointer < n:
		if my_dict.get(s[pointer]):
			stack.append('x')
			pointer = pointer + 1
		elif len(stack) < 1:
			count = count + 1
			s = s[:pointer] + s[pointer + 1:] + s[pointer]
			continue
		else:
			stack.pop()
			pointer = pointer + 1
			continue
	return count
for i in range(T):
	print(main())


for i in range(int(input())):
	a = input()
	l = input()
	bl = 0
	x = 0
	for j in l:
		if j == '(':
			bl += 1
		else:
			bl -= 1
			if bl < 0:
				bl = 0
				x += 1
	print(x)


n = int(input())
for i in range(n):
	a = int(input())
	l = input()
	count1 = 0
	for j in l:
		if j == '(':
			count1 += 1
		elif j == ')' and count1 > 0:
			count1 -= 1
	print(count1)


def fast(s):
	minBalance = float('inf')
	balance = 0
	for ch in s:
		if ch == '(':
			balance += 1
		else:
			balance -= 1
		minBalance = min(minBalance, balance)
	result = abs(minBalance)
	return result

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		result = fast(s)
		print(result)
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input().rstrip()
	op = 0
	cl = 0
	move = 0
	for i in s:
		if i == '(':
			op += 1
		else:
			cl += 1
			if cl > op:
				move = max(move, cl - op)
	print(move)


a = int(input())
for x in range(a):
	b = int(input())
	c = input()
	h = 0
	p = 0
	for y in c:
		if h <= 0 and y == ')':
			p += 1
		elif y == '(':
			h += 1
		else:
			h -= 1
	print(p)


def solve():
	n = int(input())
	s = input()
	temp = []
	for ele in s:
		if len(temp) == 0:
			temp.append(ele)
		elif ele == ')' and temp[-1] == '(':
			temp.pop()
		else:
			temp.append(ele)
	print(int(len(temp) / 2))
	return 0
t = int(input())
for _ in range(t):
	solve()


import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left, bisect_right
import threading
from collections import Counter, defaultdict
arr = []

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		op = 0
		cnt = 0
		for ch in s:
			if ch == ')' and op > 0:
				cnt += 1
				op -= 1
			elif ch == '(':
				op += 1
				cnt += 1
		print(n - cnt)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for i in range(int(input())):
	n = int(input())
	string = input()
	bal = 0
	count = 0
	for j in string:
		if j == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				count += 1
	print(count)


test = int(input())
for i in range(test):
	n = int(input())
	s = input()
	balance = 0
	l_cnt = 0
	for i in range(n):
		if s[i] == '(':
			balance += 1
		elif balance <= 0:
			l_cnt += 1
		else:
			balance -= 1
	r_cnt = 0
	balance = 0
	for i in range(n - 1, -1, -1):
		if s[i] == ')':
			balance += 1
		elif balance <= 0:
			r_cnt += 1
		else:
			balance -= 1
	print(min(l_cnt, r_cnt))


import math
import random
from collections import *
mod = 1000000007
r1 = lambda : int(input())
rm = lambda : map(int, input().split())
rms = lambda : map(str, input().split())
rls = lambda : list(rm())

def def_value():
	return 'nan'

def solve():
	test = r1()
	while test:
		test -= 1
		n = r1()
		s = list(input())
		ls = []
		ans = 0
		for i in s:
			if i == ')' and len(ls) == 0:
				ans += 1
				continue
			if i == '(':
				ls.append('(')
			else:
				ls.pop()
		ans += len(ls)
		print(ans // 2)
solve()


for _ in range(int(input())):
	n = int(input())
	st = input()
	while '()' in st:
		sr = st.find('()')
		if len(st) == sr + 2:
			st = st[:sr]
		else:
			st = st[0:sr] + st[sr + 2:]
	print(len(st) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	q = []
	for i in s:
		if i == '(':
			q.append(i)
		elif q:
			if q[-1] == '(':
				q.pop()
	print(len(q))


t = input()
for i in range(int(t)):
	n = input()
	s = input()
	open_cnt = 0
	close_cnt = 0
	moves = 0
	for c in s[:len(s)]:
		if c == ')':
			close_cnt += 1
			if open_cnt > 0:
				open_cnt -= 1
				close_cnt -= 1
		else:
			open_cnt += 1
	print(close_cnt)


t = int(input())
for _ in range(t):
	n = int(input())
	brackets = list(input())
	ans = 0
	bal = 0
	for i in range(0, n):
		if brackets[i] == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				bal = 0
				ans += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = list(s)
	i = 0
	while i < len(l) - 1:
		if l[i] == '(' and l[i + 1] == ')':
			del l[i]
			del l[i]
			if i == 0:
				i -= 1
			else:
				i -= 2
		i += 1
	print(len(l) // 2)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip()
	lv = 0
	bottom = 0
	for ch in s:
		if ch == ')':
			lv -= 1
		else:
			lv += 1
		bottom = min(bottom, lv)
	print(abs(bottom))


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	ans = 0
	for i in range(n):
		cnt += s[i] == '('
		cnt -= s[i] == ')'
		ans = min(ans, cnt)
	print(-ans)


t = int(input())

def move_bracket(s):
	i = 0
	while True:
		if i == len(s) - 1 or len(s) == 0:
			break
		if s[i:i + 2] == '()':
			s = s[0:i] + s[i + 2:]
			i = 0
		else:
			i = i + 1
	return len(s) // 2
for i in range(0, t):
	n = int(input())
	s = input()
	print(move_bracket(s))


for _ in range(int(input())):
	n = int(input())
	a = input()
	s = a.split('()')
	s = ''.join(s)
	while '()' in s:
		a = s.split('()')
		s = ''.join(a)
	print(int(len(s) / 2))


from sys import stdin, stdout
q = int(input())
for i in range(q):
	n = int(input())
	a = input()
	st = []
	i = 0
	n = len(a)
	while i < n:
		if a[i] == '(':
			st.append(a[i])
		elif len(st) > 0 and st[-1] == '(':
			st.pop()
		else:
			st.append(a[i])
		i += 1
	print(len(st) // 2)


def main():
	t = int(input())
	for g in range(t):
		n = int(input())
		s = input()
		count = 0
		ans = 0
		for i in s:
			if i == '(':
				count += 1
			else:
				count -= 1
				if count < 0:
					count = 0
					ans += 1
		print(ans)
main()


for t in range(int(input())):
	n = int(input())
	s = input()
	m = d = 0
	for i in range(n):
		if s[i] == '(':
			d += 1
		else:
			d -= 1
			if d < m:
				m = d
	print(-m)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	l = list(s)
	ans = 0
	op = cl = 0
	for i in range(len(l)):
		if l[i] == ')':
			cl = cl + 1
		else:
			op = op + 1
		if op > 0:
			if l[i] == ')':
				op = op - 1
		elif l[i] == ')':
			ans = ans + 1
	print(ans)


for t in range(int(input())):
	(n, s) = (int(input()), input())
	cnt = 0
	for i in s:
		if i == '(':
			cnt += 1
		elif cnt > 0 and i == ')':
			cnt -= 1
	print(cnt)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	x = 0
	y = 0
	p = 0
	for i in s:
		if i == '(':
			x += 1
		else:
			x -= 1
		if x < p and x < 0:
			y += 1
			x += 1
		p = x
	print(y)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

def array():
	return list(map(int, sys.stdin.readline().split()))

def intt():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(input())
from itertools import permutations as pmt
from collections import Counter
from collections import Counter
from collections import deque
for i in range(int(input())):
	n = int(input())
	s = input()
	cnt = 0
	m = 0
	for i in s:
		if i == '(':
			cnt += 1
		else:
			cnt -= 1
		m = min(m, cnt)
	print(abs(m))


for _ in range(int(input())):
	n = int(input())
	s = input()
	max1 = 0
	c = 0
	o = 0
	for i in range(0, len(s)):
		if s[i] == ')':
			c = c + 1
		if s[i] == '(':
			o = o + 1
		if c > o and abs(o - c) > max1:
			max1 = abs(o - c)
	print(max1)


for _ in range(int(input())):
	n = int(input())
	s = 0
	r = 0
	for c in input():
		if c == '(':
			s += 1
		elif not s:
			r += 1
		else:
			s -= 1
	print(r)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	bracket = 0
	bracket_max = 0
	for c in s:
		if c == ')' and bracket <= 0:
			bracket -= 1
			bracket_max = max(bracket_max, abs(bracket))
		elif c == ')':
			bracket -= 1
		elif c == '(':
			bracket += 1
	print(bracket_max)


from math import floor

def ba(expr):
	lenn = len(expr)
	if lenn % 2:
		return -1
	s = []
	for i in range(lenn):
		if expr[i] == ')' and len(s):
			if s[0] == '(':
				s.pop(0)
			else:
				s.insert(0, expr[i])
		else:
			s.insert(0, expr[i])
	red_len = len(s)
	n = 0
	while len(s) and s[0] == '(':
		s.pop(0)
		n += 1
	return floor(red_len // 2)
t = int(input())
for i in range(t):
	n = int(input())
	st = input()
	c = 0
	c = ba(st)
	print(c)


from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	a = 0
	for i in range(n):
		if s[i] == '(':
			a += 1
		else:
			a -= 1
		ans = min(ans, a)
	print(abs(ans))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	v = 0
	minv = 0
	for char in s:
		if char == '(':
			v += 1
		else:
			v -= 1
			if v < minv:
				minv = v
	print(-minv)


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	(res_cb, res_ob) = (0, 0)
	(op, cl) = (0, 0)
	for c in s:
		if c == '(':
			op += 1
		elif op == 0:
			res_cb += 1
		else:
			op -= 1
	s = s[::-1]
	for c in s:
		if c == ')':
			cl += 1
		elif cl == 0:
			res_ob += 1
		else:
			cl -= 1
	print(res_cb + abs(res_cb - res_ob))


t = int(input())
for qwe in range(t):
	n = int(input())
	s = str(input())
	otc = 0
	zac = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			otc += 1
		elif s[i] == ')':
			zac += 1
		if zac > otc:
			ans += 1
			zac -= 1
	print(ans)


for nt in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	ans = 0
	for i in range(n):
		if len(stack) == 0:
			if s[i] == ')':
				s += ')'
				ans += 1
			else:
				stack.append('(')
		elif s[i] == ')':
			stack.pop()
		else:
			stack.append('(')
	print(ans)


cases = int(input())
for _ in range(cases):
	n = int(input())
	arr = input().strip()
	count = 0
	opens = 0
	for i in range(n):
		if arr[i] == '(':
			opens += 1
		elif opens == 0:
			count += 1
		else:
			opens -= 1
	print(count)


from sys import stdin, stdout
input = stdin.readline

def solve(cs):
	n = int(input())
	s = input()
	x = 0
	mn = 0
	for i in range(n):
		if s[i] == '(':
			x += 1
		else:
			x -= 1
		mn = min(mn, x)
	print(max(abs(mn), abs(x)))
for tc in range(int(input())):
	solve(tc + 1)


T = int(input())
for i in range(T):
	n = int(input())
	s = input()
	num = 0
	k = 0
	for j in s:
		if j == '(':
			k += 1
		elif k == 0:
			num += 1
		else:
			k -= 1
	print(num)


for _ in range(int(input())):
	x = int(input())
	s = input()
	for num in range(x):
		s = s.replace('()', '')
	print(len(s) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	r = 0
	x = 0
	for j in s:
		if j == '(':
			r += 1
		elif r > 0 and j == ')':
			r -= 1
		elif j == ')':
			s = s[:] + ')'
			x += 1
	print(x)


t = int(input())
for i in range(t):
	n = int(input())
	string = input()
	s = []
	ans = 0
	for j in range(n):
		if len(s) > 0 or string[j] == '(':
			if string[j] == '(':
				s.append('(')
			else:
				s.pop()
		else:
			ans += 1
	print(ans)


from sys import stdout, stdin
input = stdin.readline
for t in range(int(input())):
	n = int(input())
	s = input().strip()
	f = []
	b = []
	for i in range(n):
		if s[i] == '(':
			f.append(i)
		elif f != []:
			f.pop()
	print(len(f))


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	co = 0
	mo = 0
	s = list(s)
	for j in range(n):
		if s[j] == '(':
			co += 1
			continue
		if s[j] == ')':
			if co >= 1:
				co -= 1
				continue
			else:
				s.append(')')
				mo += 1
				continue
	ans.append(mo)
for an in ans:
	print(an)


t = int(input())
a = []
for i in range(t):
	n = int(input())
	s = input()
	while '()' in s:
		s = s.replace('()', '')
	a.append(len(s) // 2)
for i in a:
	print(i)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = []
	c = 0
	s = input()
	for ele in s:
		if ele == '(':
			a.append(ele)
		elif len(a) != 0:
			a.pop()
		else:
			c += 1
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	seq = list(input())
	cnt = 0
	bad = 0
	for i in range(n):
		if cnt == 0 and seq[i] == ')':
			cnt = 0
			bad += 1
		elif seq[i] == ')':
			cnt -= 1
		else:
			cnt += 1
	print(bad)


def solution(x):
	while '()' in x:
		x = x.replace('()', '')
	return len(x) // 2

def main():
	for test in range(int(input())):
		_ = input()
		s = input()
		result = solution(s)
		print(result)
main()


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input()
	pointer = 0
	while s.find('()') != -1:
		s = s.replace('()', '')
	if len(s) == 0:
		ans.append(0)
	else:
		ans.append(len(s) // 2)
for i in ans:
	print(i)


for _ in ' ' * int(input()):
	a = int(input())
	b = input()
	while '()' in b:
		b = b.replace('()', '')
	print(len(b) // 2)


amountTests = int(input())
ans = ''
for x in range(amountTests):
	size = int(input())
	brackets = input()
	open_ = []
	close = []
	for bck in range(len(brackets)):
		if brackets[bck] == '(':
			open_.append(bck)
		elif len(open_) > 0:
			open_.pop(-1)
		else:
			close.append(bck)
	if len(close) != len(open_):
		print(-1)
	else:
		ans += str(len(open_)) + '\n'
print(ans)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for _ in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, s):
	need_to_move = 0
	brackets = 0
	for (i, item) in enumerate(s):
		if item == '(':
			brackets += 1
		elif item == ')':
			brackets -= 1
			if brackets < 0:
				need_to_move += 1
				brackets += 1
	assert brackets == need_to_move
	return need_to_move
for i in tests():
	n = int_in()
	s = str_in()
	out(solve(n, s))


t = int(input())
for _ in range(t):
	n = int(input())
	S = input()
	l = 0
	cnt = 0
	for i in range(n):
		if S[i] == '(':
			l += 1
		elif l == 0:
			cnt += 1
		else:
			l -= 1
	print(cnt)


import sys
from fractions import gcd
from math import ceil, sqrt, sin, pi, tan
from collections import defaultdict
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())
as0 = ord('0')
as1 = ord('1')
for _ in range(cin()):
	n = cin()
	s = read()
	st = []
	for i in range(n):
		if s[i] == ord('('):
			st.append(s[i])
		elif st and st[-1] == ord('('):
			st.pop()
		else:
			st.append(s[i])
	print(len(st) // 2)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	suma = minimum = 0
	for znak in s:
		if znak == ')' and suma == 0:
			minimum += 1
		elif znak == '(':
			suma += 1
		elif znak == ')':
			suma -= 1
	print(minimum)


q = int(input())
while q > 0:
	g = input()
	s = input()
	s = s.strip()
	while True:
		if '()' in s:
			s = s.replace('()', '')
		else:
			break
	print(int(len(s) / 2))
	q -= 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(l, r) = (0, 0)
	for j in range(n):
		if s[j] == '(':
			l += 1
		if s[j] == ')':
			r += 1
			if l > 0:
				l -= 1
				r -= 1
	print(min(l, r))


from math import log2
for _ in range(int(input())):
	n = int(input())
	l = list(input())
	op = 0
	ans = 0
	for i in range(len(l)):
		if l[i] == '(':
			op += 1
		elif l[i] == ')' and op == 0:
			ans += 1
		elif l[i] == ')' and op > 0:
			op -= 1
	print(ans)


import sys
input = sys.stdin.readline
from math import ceil
answer = []
for kek in range(int(input())):
	n = int(input())
	s = input()
	a = 0
	m = 0
	for i in s:
		if i == '(':
			a += 1
		if i == ')':
			a -= 1
		m = min(a, m)
	answer.append(-m)
print(*answer, sep='\n')


for _ in range(int(input())):
	i = int(input())
	x = input()
	if '()' not in x:
		print(i // 2)
	else:
		while '()' in x:
			a = x.index('()')
			if a == i - 2:
				x = x[:a]
			else:
				x = x[:a] + x[a + 2:]
		print(len(x) // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	sch = 0
	ans = 0
	for x in s:
		if x == '(':
			sch += 1
		else:
			sch -= 1
		ans = min(ans, sch)
	print(-ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	s1 = s[:]
	l = []
	c = 0
	for i in s:
		if i == '(':
			l.append(i)
		elif i == ')':
			if len(l) == 0:
				c += 1
			else:
				l.pop()
	print(c)


from itertools import accumulate
tc = int(input())
while tc > 0:
	n = int(input())
	print(abs(min(accumulate([-1 if c == ')' else 1 for c in input()]))))
	tc -= 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	stack = []
	remove = set()
	for (i, c) in enumerate(s):
		if c == '(':
			stack.append(c)
		elif stack and stack[-1] == '(':
			stack.pop()
		elif not stack:
			remove.add(i)
	print(len(remove))


thms = int(input())
for ihms in range(thms):
	nhms = int(input())
	shms = input()
	chms = 0
	ohms = 0
	for jhms in range(nhms):
		if shms[jhms] == '(':
			ohms = ohms + 1
		elif ohms == 0:
			chms = chms + 1
		else:
			ohms = ohms - 1
	print(chms)


t = int(input())
for i in range(t):
	n = int(input())
	s = input().strip()
	o = 0
	m = 0
	for v in s:
		if v == '(':
			o = o + 1
		elif v == ')':
			if o >= 1:
				o = o - 1
			else:
				m = m + 1
	print(m)


t = int(input())
for i in range(t):
	n = int(input())
	l = input()
	left = 0
	right = 0
	count = 0
	flag = 0
	for j in l:
		if j == '(':
			left += 1
		if j == ')':
			right += 1
		if right > left:
			count += 1
			right -= 1
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	result = 0
	stack = []
	for c in s:
		if c == '(':
			stack.append('(')
		elif len(stack) == 0:
			result += 1
		else:
			stack.pop()
	print(result)


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	p = [0]
	for x in s:
		if x == '(':
			p.append(p[-1] + 1)
		else:
			p.append(p[-1] - 1)
	print(-min(p))


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	(op, cl, ans) = (0, 0, 0)
	for i in range(n):
		ch = s[i]
		if ch == '(':
			op += 1
		elif op > 0:
			op -= 1
		else:
			ans += 1
	print(ans)


num = int(input())
for i in range(num):
	mm = int(input())
	n = input()
	count = 0
	final = []
	for i in n:
		if i == ')':
			if len(final) > 0 and final[-1] == '(':
				final.pop()
			else:
				count += 1
		if i == '(':
			final.append(i)
	print(count)


t = int(input())
for _ in range(0, t):
	n = int(input())
	s = input()
	c = 0
	op = 0
	ed = 0
	for i in s:
		if i == '(':
			op += 1
		else:
			ed += 1
		if op == ed:
			op = 0
			ed = 0
		elif ed > op:
			ed = 0
			op = 0
			c += 1
		else:
			continue
	print(c)


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	s = input().strip()
	l = []
	for i in range(len(s)):
		l.append(s[i])
	j = 0
	p = len(l)
	while j < p - 1:
		if l[j] == '(' and l[j + 1] == ')':
			l.pop(j)
			l.pop(j)
			j = 0
		else:
			j += 1
		p = len(l)
	y = len(l) // 2
	ans.append(y)
for k in ans:
	print(k)


try:
	t = int(input())
	for v in range(t):
		n = int(input())
		a = list(input())
		len = 0
		for i in range(n):
			if a[i] == '(':
				len += 1
			if a[i] == ')' and len:
				len -= 1
		print(len)
except:
	pass


for i in range(int(input())):
	n = int(input())
	s = input()
	c = 0
	v = 0
	for i in s:
		if i == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			v = min(v, c)
	print(abs(v))


t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	a = 0
	ans = 0
	for j in range(n):
		if s[j] == ')':
			a -= 1
		else:
			a += 1
		ans = min(a, ans)
	print(abs(ans))


t = int(input())
for _ in range(t):
	n = int(input())
	s = list(input())
	stack = 0
	for i in range(n):
		if s[i] == '(':
			stack += 1
		elif stack > 0:
			stack -= 1
	print(stack)


n = int(input())
for j in range(0, n):
	m = int(input())
	s = str(input())
	clos = 0
	ope = 0
	for i in s:
		if i == '(':
			ope += 1
		elif i == ')':
			if ope > 0:
				ope -= 1
			else:
				clos -= 1
	print(abs(clos))


n = int(input())
c = 0
r = 0
s = ''
for i in range(n):
	input()
	s = input()
	for j in s:
		if c < 0:
			r += 1
			c += 1
		if j == '(':
			c += 1
		elif j == ')':
			c -= 1
	print(r)
	r = 0
	c = 0


for t in range(int(input())):
	N = int(input())
	s = input()
	sum = 0
	move = 0
	l = []
	l2 = []
	for i in s:
		l.append(i)
	for i in range(N):
		if l[i] == '(':
			sum += 1
		else:
			sum -= 1
			if sum < 0:
				move += 1
				sum = 0
	print(move)


def sol3():
	for t in range(int(input())):
		n = int(input())
		s = list(input())
		opn = wrg = 0
		for i in s:
			if i == '(':
				opn += 1
			else:
				opn -= 1
			if opn < 0:
				wrg += 1
				opn = 0
		print(wrg)
sol3()


for iii in range(int(input())):
	input()
	s = input()
	while s.count('()') != 0:
		s = s.replace('()', '')
	print(len(s) // 2)