File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-04/sol/Apoorv012 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments