using
System;
using
System.Collections.Generic;
class
GFG{
static
void
constructBalanceArray(
int
[] BOP,
int
[] BCP,
String str,
int
n)
{
Stack<
int
> stk =
new
Stack<
int
>();;
for
(
int
i = 0; i < n; i++)
{
if
(str[i] ==
'('
)
stk.Push(i);
else
{
if
(stk.Count != 0)
{
BCP[i] = 1;
BOP[stk.Peek()] = 1;
stk.Pop();
}
else
BCP[i] = 0;
}
}
for
(
int
i = 1; i < n; i++)
{
BCP[i] += BCP[i - 1];
BOP[i] += BOP[i - 1];
}
}
static
int
query(
int
[] BOP,
int
[] BCP,
int
s,
int
e)
{
if
(BOP[s - 1] == BOP[s])
{
return
(BCP[e] - BOP[s]) * 2;
}
else
{
return
(BCP[e] - BOP[s] + 1) * 2;
}
}
public
static
void
Main(String[] args)
{
String str =
"())(())(())("
;
int
n = str.Length;
int
[] BCP =
new
int
[n + 1];
int
[] BOP =
new
int
[n + 1];
constructBalanceArray(BOP, BCP, str, n);
int
startIndex = 5, endIndex = 11;
Console.Write(
"Maximum Length Correct "
+
"Bracket Subsequence between "
+
startIndex +
" and "
+ endIndex +
" = "
+
query(BOP, BCP, startIndex, endIndex) +
"\n"
);
startIndex = 4;
endIndex = 5;
Console.Write(
"Maximum Length Correct "
+
"Bracket Subsequence between "
+
startIndex +
" and "
+ endIndex +
" = "
+
query(BOP, BCP, startIndex, endIndex) +
"\n"
);
startIndex = 1;
endIndex = 5;
Console.Write(
"Maximum Length Correct "
+
"Bracket Subsequence between "
+
startIndex +
" and "
+ endIndex +
" = "
+
query(BOP, BCP, startIndex, endIndex) +
"\n"
);
}
}