Maximize Number of Subsequences in a String LeetCode solution in C++

1
class Solution {
2
public:
3
long long maximumSubsequenceCount(string text, string pattern) {
4
// support variables
5
int len = text.size();
6
long long res = 0, aCount = 0, bCount = 0;
7
char a = pattern[0], b = pattern[1];
8
// getting the frequencies
9
for (char c : text) {
10
if (c == a)
11
aCount++;
12
else if (c == b)
13
bCount++;
14
}
15
// edge case: a == b
16
if (a == b) return aCount++ * aCount / 2;
17
// adding our extra character to maximise the occurrences
18
if (aCount < bCount)
19
res += bCount;
20
else
21
bCount++;
22
// computing the occurrences
23
for (char c : text) {
24
// first case: spotting the first element of a sequence
25
if (c == a) {
26
res += bCount;
27
}
28
// second case: we found an ending sequence
29
else if (c == b)
30
bCount--;
31
// all the rest: we do nothing
32
}
33
return res;
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0