We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 97c6f46 commit d466217Copy full SHA for d466217
1 file changed
Problems/Data-structures/Day-04/sol/DoonMad/q001.cpp
@@ -0,0 +1,36 @@
1
+#include<bits/stdc++.h>
2
+
3
+using namespace std;
4
5
+void solve(){
6
+ int n; cin>>n;
7
+ string s; cin>>s;
8
+ stack<int> st;
9
+ long long res=0;
10
11
+ st.push(0); // inserting first element (always a '(')
12
+ for(int i=1; i<n; i++){
13
+ // trying to close a pair immediately to minimize distance (greedy)
14
+ if(s[i] == ')' || (s[i] == '_' && !st.empty())){
15
+ res += (i-st.top());
16
+ st.pop();
17
+ }
18
+ else{
19
+ st.push(i);
20
21
22
23
+ cout<<res<<endl;
24
+}
25
26
+// Time Complexity: O(N)
27
+// Space Complexity: O(N) (string + stack)
28
29
+int main(int argc, char const *argv[])
30
+{
31
+ int t; cin>>t;
32
+ while(t--){
33
+ solve();
34
35
+ return 0;
36
0 commit comments