Skip to content

Commit d2d9633

Browse files
authored
Create maximum-score-from-removing-substrings.cpp
1 parent a48425d commit d2d9633

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maximumGain(string s, int x, int y) {
7+
string a = "ab", b = "ba";
8+
if (x < y) {
9+
swap(a, b);
10+
swap(x, y);
11+
}
12+
return remove(s, a, x) + remove(s, b, y);
13+
}
14+
15+
private:
16+
int remove(string &s, string a, int x) {
17+
int i = 0, result = 0;
18+
for (int j = 0; j < size(s); ++j) {
19+
s[i++] = s[j];
20+
if (i >= 2 && s.substr(i - 2, 2) == a) {
21+
i -= 2;
22+
result += x;
23+
}
24+
}
25+
s.resize(i);
26+
return result;
27+
}
28+
};

0 commit comments

Comments
 (0)