3628. Maximum Number of Subsequences After One Inserting
Description
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 <= 105
s
consists of uppercase English letters.
Solutions
Solution 1: Enumeration
We can first calculate the number of "LCT" subsequences in the original string, then consider the case of inserting one letter.
The number of "LCT" subsequences can be calculated by traversing the string. We can enumerate the middle "C" and use two variables \(l\) and \(r\) to maintain the counts of "L" on the left and "T" on the right respectively. For each "C", we can calculate the number of "L"s on its left and the number of "T"s on its right, thus obtaining the number of "LCT" subsequences with this "C" as the middle character as \(l \times r\), and accumulate it to the total count.
Next, we need to consider the case of inserting one letter. Consider inserting an "L", "C", or "T":
- Insert an "L": we only need to count the number of "CT" subsequences in the original string.
- Insert a "T": we only need to count the number of "LC" subsequences in the original string.
- Insert a "C": we only need to count the number of "LT" subsequences in the original string. In this case, during the enumeration process above, we can maintain a variable \(\textit{mx}\) representing the current maximum value of \(l \times r\).
Finally, we add the number of "LCT" subsequences in the original string to the maximum number of subsequences after inserting one letter to get the final result.
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
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 36 37 |
|
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 |
|
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 36 37 38 |
|
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 |
|