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;
    int count1 = 0;

    for (int i = 0; i < text.length(); ++i) {
      if (text[i] == pattern[1]) {
        ans += count0;
        ++count1;
      }
      if (text[i] == pattern[0])
        ++count0;
    }

    // Adding pattern[0] in the beginning or
    // Adding pattern[1] in the end is optimal
    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;
    int count1 = 0;

    for (int i = 0; i < text.length(); ++i) {
      if (text.charAt(i) == pattern.charAt(1)) {
        ans += count0;
        ++count1;
      }
      if (text.charAt(i) == pattern.charAt(0))
        ++count0;
    }

    // Adding pattern.charAt(0) in the beginning or
    // Adding pattern.charAt(1) in the end is optimal
    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
    count1 = 0

    for i, c in enumerate(text):
      if c == pattern[1]:
        ans += count0
        count1 += 1
      if c == pattern[0]:
        count0 += 1

    # Adding pattern[0] in the beginning or
    # Adding pattern[1] in the end is optimal
    return ans + max(count0, count1)