[LeetCode] Maximum Score From Removing Substrings

1717. Maximum Score From Removing Substrings

You are given a string s and two integers x and y. You can perform two types of operations any number of times.

  • Remove substring “ab” and gain x points.
  • For example, when removing “ab” from “cabxbae” it becomes “cxbae”.
  • Remove substring “ba” and gain y points.
  • For example, when removing “ba” from “cabxbae” it becomes “cabxe”.

Return the maximum points you can gain after applying the above operations on s.

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
class Solution {
pair<string, int> AB(string& s, int p) {
string ss = "";
int res = 0;
for(auto& ch : s) {
if(ch == 'b' and !ss.empty() and ss.back() == 'a') {
ss.pop_back();
res += p;
} else ss.push_back(ch);
}
return {ss,res};
}
pair<string, int> BA(string& s, int p) {
string ss = "";
int res = 0;
for(auto& ch : s) {
if(ch == 'a' and !ss.empty() and ss.back() == 'b') {
ss.pop_back();
res += p;
} else ss.push_back(ch);
}
return {ss,res};
}
public:
int maximumGain(string s, int x, int y) {
if(x > y) {
auto [ss, res1] = AB(s,x);
auto [_,res2] = BA(ss,y);
return res1 + res2;
}
auto [ss, res1] = BA(s,y);
auto [_, res2] = AB(ss,x);
return res1 + res2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/25/PS/LeetCode/maximum-score-from-removing-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.