Skip to content

Commit 244cfd1

Browse files
committed
Day 4 Solution 1
1 parent 97c6f46 commit 244cfd1

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
3+
We have to find the minimum cost that we could acheive by placing ( and ) in the blank spaces. We have to make sure that () are valid.
4+
5+
I saw the pattern, that we can set the blank to ) as long as there is atleast one open (.
6+
7+
Time: O(n);
8+
Space: O(n);
9+
10+
Submission Link: https://codeforces.com/contest/1997/submission/355679346
11+
12+
*/
13+
14+
#include <bits/stdc++.h>
15+
using namespace std;
16+
17+
using ll = long long;
18+
19+
void solve() {
20+
ll n;
21+
cin >> n;
22+
string s;
23+
cin >> s;
24+
25+
// cout << "n, s: " << n << " " << s << endl;
26+
27+
ll ans = 0;
28+
stack<ll> st;
29+
for (ll i = 0; i < n; i++) {
30+
if (s[i] == '(') {
31+
st.push(i);
32+
// cout << i << " pushed (\n";
33+
}
34+
else if (s[i] == ')') {
35+
if (st.empty()) {
36+
cout << -1 << endl;
37+
return;
38+
}
39+
ll start = st.top();
40+
st.pop();
41+
ans += i - start;
42+
// cout << i << " poped )\n";
43+
}
44+
else {
45+
if (st.empty()) {
46+
st.push(i);
47+
// cout << i << " pushed _\n";
48+
}
49+
else {
50+
ll start = st.top();
51+
st.pop();
52+
ans += i - start;
53+
// cout << i << " popped _\n";
54+
}
55+
}
56+
}
57+
58+
cout << ans << endl;
59+
}
60+
61+
int main() {
62+
int t;
63+
cin >> t;
64+
while (t--) {
65+
solve();
66+
// cout << t << " done\n";
67+
}
68+
}

0 commit comments

Comments
 (0)