#3628

Maximum Number of Subsequences After One Inserting

Medium
StringDynamic ProgrammingGreedyPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can precompute counts of 'L', 'LC', 'T', and 'CT' at each position to efficiently calculate the maximum subsequences after one insertion.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute arrays for counts of 'L', 'LC', 'T', and 'CT' at each index.
  2. 2Step 2: Calculate the base count of 'LCT' subsequences without insertion.
  3. 3Step 3: For each position, compute potential counts by inserting 'L', 'C', or 'T' and find the maximum.
solution.py14 lines
1def maxSubsequences(s):
2    n = len(s)
3    preL, preLC, sufT, sufCT = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1), [0] * (n + 1)
4    for i in range(n):
5        preL[i + 1] = preL[i] + (s[i] == 'L')
6        preLC[i + 1] = preLC[i] + (s[i] == 'C') * preL[i + 1]
7    for i in range(n - 1, -1, -1):
8        sufT[i] = sufT[i + 1] + (s[i] == 'T')
9        sufCT[i] = sufCT[i + 1] + (s[i] == 'C') * sufT[i + 1]
10    base = sum(preLC[i] * sufT[i] for i in range(n + 1))
11    max_count = base
12    for i in range(n + 1):
13        max_count = max(max_count, preLC[i] * (sufT[i] + 1) + (preL[i] + 1) * sufCT[i])
14    return max_count

Complexity note: We only traverse the string a few times, leading to linear time complexity. Space is used for counting arrays.

  • 1Precomputation of counts allows efficient subsequence calculation.
  • 2Inserting at strategic positions maximizes subsequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.