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.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Greedy
Example 1
"LMCT"
Example 2
"LCCT"
Example 3
"L"
Step 02
Core Insight
What unlocks the optimal approach
Precompute <code>preL</code>, <code>preLC</code>, <code>sufT</code>, and <code>sufCT</code> arrays to count L’s, LC’s, T’s, and CT’s at each position.
Compute <code>base</code> as the sum over all i of <code>preLC[i] * sufT[i]</code>.
For each insert position i, compute gains <code>sufCT[i]</code> for ‘L’, <code>preL[i] * sufT[i]</code> for ‘C’, and <code>preLC[i]</code> for ‘T’, and take the maximum of <code>base</code> and <code>base + gain</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
class Solution {
private char[] s;
public long numOfSubsequences(String S) {
s = S.toCharArray();
int l = 0, r = 0;
for (char c : s) {
if (c == 'T') {
++r;
}
}
long ans = 0, mx = 0;
for (char c : s) {
r -= c == 'T' ? 1 : 0;
if (c == 'C') {
ans += 1L * l * r;
}
l += c == 'L' ? 1 : 0;
mx = Math.max(mx, 1L * l * r);
}
mx = Math.max(mx, Math.max(calc("LC"), calc("CT")));
ans += mx;
return ans;
}
private long calc(String t) {
long cnt = 0;
int a = 0;
for (char c : s) {
if (c == t.charAt(1)) {
cnt += a;
}
a += c == t.charAt(0) ? 1 : 0;
}
return cnt;
}
}
// Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
func numOfSubsequences(s string) int64 {
calc := func(t string) int64 {
cnt, a := int64(0), int64(0)
for _, c := range s {
if c == rune(t[1]) {
cnt += a
}
if c == rune(t[0]) {
a++
}
}
return cnt
}
l, r := int64(0), int64(0)
for _, c := range s {
if c == 'T' {
r++
}
}
ans, mx := int64(0), int64(0)
for _, c := range s {
if c == 'T' {
r--
}
if c == 'C' {
ans += l * r
}
if c == 'L' {
l++
}
mx = max(mx, l*r)
}
mx = max(mx, calc("LC"), calc("CT"))
ans += mx
return ans
}
# Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
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
// Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
// class Solution {
// private char[] s;
//
// public long numOfSubsequences(String S) {
// s = S.toCharArray();
// int l = 0, r = 0;
// for (char c : s) {
// if (c == 'T') {
// ++r;
// }
// }
// long ans = 0, mx = 0;
// for (char c : s) {
// r -= c == 'T' ? 1 : 0;
// if (c == 'C') {
// ans += 1L * l * r;
// }
// l += c == 'L' ? 1 : 0;
// mx = Math.max(mx, 1L * l * r);
// }
// mx = Math.max(mx, Math.max(calc("LC"), calc("CT")));
// ans += mx;
// return ans;
// }
//
// private long calc(String t) {
// long cnt = 0;
// int a = 0;
// for (char c : s) {
// if (c == t.charAt(1)) {
// cnt += a;
// }
// a += c == t.charAt(0) ? 1 : 0;
// }
// return cnt;
// }
// }
// Accepted solution for LeetCode #3628: Maximum Number of Subsequences After One Inserting
function numOfSubsequences(s: string): number {
const calc = (t: string): number => {
let [cnt, a] = [0, 0];
for (const c of s) {
if (c === t[1]) cnt += a;
if (c === t[0]) a++;
}
return cnt;
};
let [l, r] = [0, 0];
for (const c of s) {
if (c === 'T') r++;
}
let [ans, mx] = [0, 0];
for (const c of s) {
if (c === 'T') r--;
if (c === 'C') ans += l * r;
if (c === 'L') l++;
mx = Math.max(mx, l * r);
}
mx = Math.max(mx, calc('LC'));
mx = Math.max(mx, calc('CT'));
ans += mx;
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.