1- // gpt
21package com .lzw .solutions .codeforces .p2190B1 ;
32
4- import java .io .BufferedReader ;
5- import java .io .InputStreamReader ;
3+ import java .util .*;
64
75public class MainPlus {
8- public static void main (String [] args ) throws Exception {
9- BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
10- StringBuilder out = new StringBuilder ();
11-
12- int t = Integer .parseInt (br .readLine ().trim ());
13- while (t -- > 0 ) {
14- int n = Integer .parseInt (br .readLine ().trim ());
15- String s = br .readLine ().trim ();
16-
17- // Precompute suffix counts of '(' and ')'
18- int [] sufOpen = new int [n + 1 ];
19- int [] sufClose = new int [n + 1 ];
20-
21- for (int i = n - 1 ; i >= 0 ; i --) {
22- sufOpen [i ] = sufOpen [i + 1 ];
23- sufClose [i ] = sufClose [i + 1 ];
24- if (s .charAt (i ) == '(' ) sufOpen [i ]++;
25- else sufClose [i ]++;
26- }
6+ public static void main (String [] args ) {
7+ Scanner sc = new Scanner (System .in );
8+ int t = sc .nextInt ();
9+
10+ for (int test = 0 ; test < t ; test ++) {
11+ int n = sc .nextInt ();
12+ String s = sc .next ();
2713
28- int answer = -1 ;
14+ int ans = -1 ;
2915
30- // Try to skip the earliest ')' that allows a valid suffix RBS
16+ // Try every possible first difference position i (0-based)
17+ // where we change s[i] from ) to (
3118 for (int i = 0 ; i < n ; i ++) {
32- if (s .charAt (i ) == ')' ) {
33- int pairs = Math .min (sufOpen [i + 1 ], sufClose [i + 1 ]);
34- if (pairs > 0 ) {
35- answer = 2 * pairs ;
19+ if (s .charAt (i ) != ')' ) continue ;
20+
21+ // simulate prefix up to i (with s[i] changed to '(' )
22+ int bal = 0 ;
23+ boolean valid = true ;
24+ for (int j = 0 ; j < i ; j ++) {
25+ bal += (s .charAt (j ) == '(' ? 1 : -1 );
26+ if (bal < 0 ) {
27+ valid = false ;
3628 break ;
3729 }
3830 }
31+ if (!valid ) continue ;
32+
33+ // now add the changed '('
34+ bal += 1 ;
35+ if (bal < 0 ) continue ; // though unlikely here
36+
37+ // now from i+1 to end, greedily take as far as possible
38+ // while keeping bal >= 0, and stop when bal returns to 0
39+ int len = i + 1 ; // 0-based: positions 0..i
40+ int startBal = bal ;
41+
42+ for (int j = i + 1 ; j < n ; j ++) {
43+ bal += (s .charAt (j ) == '(' ? 1 : -1 );
44+ if (bal < 0 ) break ;
45+ len ++;
46+ if (bal == 0 ) {
47+ // found a valid completion
48+ ans = Math .max (ans , len );
49+ break ; // no need to go further — longer won't be prefix-equal
50+ }
51+ }
3952 }
4053
41- out .append ( answer ). append ( '\n' );
54+ System . out .println ( ans );
4255 }
43-
44- System .out .print (out .toString ());
56+ sc .close ();
4557 }
46- }
58+ }
0 commit comments