-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximumScoreFromRemovingSubstrings.cpp
More file actions
43 lines (42 loc) · 1.05 KB
/
maximumScoreFromRemovingSubstrings.cpp
File metadata and controls
43 lines (42 loc) · 1.05 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
// Source: https://leetcode.com/problems/maximum-score-from-removing-substrings/
// Author: Miao Zhang
// Date: 2021-05-31
class Solution {
public:
int maximumGain(string s, int x, int y) {
stack<char> st, st1;
int res = 0;
if (x > y) {
swap(x, y);
reverse(s.begin(), s.end());
}
// ba
for (char& c: s) {
if (c != 'a') {
st.push(c);
} else {
if (!st.empty() && st.top() == 'b') {
st.pop();
res += y;
} else {
st.push(c);
}
}
}
// ab
while (!st.empty()) {
char c = st.top();
st.pop();
if (c != 'a') st1.push(c);
else {
if (!st1.empty() && st1.top() == 'b') {
st1.pop();
res += x;
} else {
st1.push(c);
}
}
}
return res;
}
};