[LeetCode] Maximize Number of Subsequences in a String

2207. Maximize Number of Subsequences in a String

You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.

You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.

Return the maximum number of times pattern can occur as a subsequence of the modified text.

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

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
class Solution {
long long helper(vector<int>& f, vector<int>& s) {
long long res = 0;
int i = 0, j = 0;
while(i < f.size() and j < s.size()) {
while(j < s.size() and f[i] > s[j]) j++;
res += s.size() - j;
i++;
}
return res;
}
public:
long long maximumSubsequenceCount(string text, string pattern) {
if(pattern[0] == pattern[1]) {
long long count = 0;
for(auto ch : text)
if(ch == pattern[0])
count++;
return count * (count + 1) / 2;
}
vector<int> f, s;
for(int i = 0; i < text.length(); i++) {
if(text[i] == pattern[0])
f.push_back(i);
else if(text[i] == pattern[1])
s.push_back(i);
}

return helper(f,s) + max(f.size(), s.size());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/maximize-number-of-subsequences-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.