Maximum Number of Subsequences After One Inserting Problem
Description
LeetCode Problem 3628.
You are given a string s consisting of uppercase English letters.
You are allowed to insert at most one uppercase English letter at any position (including the beginning or end) of the string.
Return the maximum number of "LCT" subsequences that can be formed in the resulting string after at most one insertion.
Example 1:
Input: s = "LMCT"
Output: 2
Explanation:
We can insert a "L" at the beginning of the string s to make "LLMCT", which has 2 subsequences, at indices [0, 3, 4] and [1, 3, 4].
Example 2:
Input: s = "LCCT"
Output: 4
Explanation:
We can insert a "L" at the beginning of the string s to make "LLCCT", which has 4 subsequences, at indices [0, 2, 4], [0, 3, 4], [1, 2, 4] and [1, 3, 4].
Example 3:
Input: s = "L"
Output: 0
Explanation:
Since it is not possible to obtain the subsequence "LCT" by inserting a single letter, the result is 0.
Constraints:
1 <= s.length <= 10^5sconsists of uppercase English letters.
Solution
Approach: Enumeration
First count the "LCT" subsequences already in the string, then add the best gain from inserting one letter.
To count them, treat each "C" as the middle: with l letters "L" before it and r letters "T" after it, it forms l * r subsequences. Keep l and r up to date while scanning.
Inserting one letter can only help in three ways:
- insert an "L" (best at the start): it gains one "LCT" per "CT" subsequence of the original;
- insert a "T" (best at the end): it gains one per "LC" subsequence;
- insert a "C": it gains
l * rat the chosen position, so we keep the maximuml * rseen during the scan.
The answer is the original count plus the largest of these three gains.
Complexity: O(n) time and O(1) space, where n is the length of the string.
class Solution:
def numOfSubsequences(self, s: str) -> int:
def calc(t: str) -> int:
cnt = a = 0
for c in s:
if c == t[1]:
cnt += a
a += int(c == t[0])
return cnt
l, r = 0, s.count("T")
ans = mx = 0
for c in s:
r -= int(c == "T")
if c == "C":
ans += l * r
l += int(c == "L")
mx = max(mx, l * r)
mx = max(mx, calc("LC"), calc("CT"))
ans += mx
return ans