-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum Score From Removing Substrings.cpp
More file actions
76 lines (66 loc) · 1.71 KB
/
Maximum Score From Removing Substrings.cpp
File metadata and controls
76 lines (66 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
public:
int solve_ba(string s, int x, int y) {
int ans = 0;
stack<char> st;
for(auto c: s) {
if(!st.empty() && c == 'a' && st.top() == 'b') {
ans += y;
st.pop();
} else {
st.push(c);
}
}
string remaining;
while (!st.empty()) {
remaining.push_back(st.top());
st.pop();
}
reverse(remaining.begin(), remaining.end());
for(auto c: remaining) {
if(!st.empty() && c == 'b' && st.top() == 'a') {
ans += x;
st.pop();
} else {
st.push(c);
}
}
return ans;
}
int solve_ab(string s, int x, int y) {
int ans = 0;
stack<char> st;
for(auto c: s) {
if(!st.empty() && c == 'b' && st.top() == 'a') {
ans += x;
st.pop();
} else {
st.push(c);
}
}
string remaining;
while (!st.empty()) {
remaining.push_back(st.top());
st.pop();
}
reverse(remaining.begin(), remaining.end());
for(auto c: remaining) {
if(!st.empty() && c == 'a' && st.top() == 'b') {
ans += y;
st.pop();
} else {
st.push(c);
}
}
return ans;
}
int maximumGain(string s, int x, int y) {
int ans = 0;
if(x > y) {
ans = solve_ab(s, x, y);
} else {
ans = solve_ba(s, x, y);
}
return ans;
}
};