#2207
Maximize Number of Subsequences in a String
MediumStringGreedyPrefix SumTwo PointersDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass to count occurrences of the pattern in the text while considering the effect of inserting each character of the pattern. This avoids the need for repeated counting and is much more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Count occurrences of pattern[0] and pattern[1] in the text using a single pass.
- 2Step 2: For each position in the text, calculate how many times the pattern would occur if we inserted pattern[0] or pattern[1].
- 3Step 3: Return the maximum count from both insertions.
solution.py11 lines
1def max_subsequences(text, pattern):
2 count_a = 0
3 count_b = 0
4 total = 0
5 for char in text:
6 if char == pattern[0]:
7 total += count_b
8 count_a += 1
9 elif char == pattern[1]:
10 count_b += 1
11 return total + count_a + count_bℹ
Complexity note: The time complexity is O(n) because we only traverse the text once to count occurrences, making it much more efficient than the brute force approach.
- 1Inserting characters can significantly change the number of subsequences.
- 2Counting subsequences efficiently requires careful tracking of character occurrences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.