Skip to content

2207. Maximize Number of Subsequences in a String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  long long maximumSubsequenceCount(string text, string pattern) {
    long long ans = 0;
    int count0 = 0;  // the count of the letter pattern[0]
    int count1 = 0;  // the count of the letter pattern[1]

    for (const char c : text) {
      if (c == pattern[1]) {
        ans += count0;
        ++count1;
      }
      if (c == pattern[0])
        ++count0;
    }

    // It is optimal to add pattern[0] at the beginning or add pattern[1] at the
    // end of the text.
    return ans + max(count0, count1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long maximumSubsequenceCount(String text, String pattern) {
    long ans = 0;
    int count0 = 0; // the count of the letter pattern[0]
    int count1 = 0; // the count of the letter pattern[1]

    for (final char c : text.toCharArray()) {
      if (c == pattern.charAt(1)) {
        ans += count0;
        ++count1;
      }
      if (c == pattern.charAt(0))
        ++count0;
    }

    // It is optimal to add pattern[0] at the beginning or add pattern[1] at the
    // end of the text.
    return ans + Math.max(count0, count1);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maximumSubsequenceCount(self, text: str, pattern: str) -> int:
    ans = 0
    count0 = 0  # the count of the letter pattern[0]
    count1 = 0  # the count of the letter pattern[1]

    for c in text:
      if c == pattern[1]:
        ans += count0
        count1 += 1
      if c == pattern[0]:
        count0 += 1

    # It is optimal to add pattern[0] at the beginning or add pattern[1] at the
    # end of the text.
    return ans + max(count0, count1)