Maximize Number of Subsequences in a String LeetCode solution in C++
1class Solution {2public:3long long maximumSubsequenceCount(string text, string pattern) {4// support variables5int len = text.size();6long long res = 0, aCount = 0, bCount = 0;7char a = pattern[0], b = pattern[1];8// getting the frequencies9for (char c : text) {10if (c == a)11aCount++;12else if (c == b)13bCount++;14}15// edge case: a == b16if (a == b) return aCount++ * aCount / 2;17// adding our extra character to maximise the occurrences18if (aCount < bCount)19res += bCount;20else21bCount++;22// computing the occurrences23for (char c : text) {24// first case: spotting the first element of a sequence25if (c == a) {26res += bCount;27}28// second case: we found an ending sequence29else if (c == b)30bCount--;31// all the rest: we do nothing32}33return res;34}35};