Skip to content

2430. Maximum Deletions on a String 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int deleteString(string s) {
    const int n = s.length();
    // lcs[i][j] := the number of the same letters of s[i..n) and s[j..n)
    vector<vector<int>> lcs(n + 1, vector<int>(n + 1));
    // dp[i] := the maximum number of operations needed to delete s[i..n)
    vector<int> dp(n, 1);

    for (int i = n - 1; i >= 0; --i)
      for (int j = i + 1; j < n; ++j) {
        if (s[i] == s[j])
          lcs[i][j] = lcs[i + 1][j + 1] + 1;
        if (lcs[i][j] >= j - i)
          dp[i] = max(dp[i], dp[j] + 1);
      }

    return dp[0];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int deleteString(String s) {
    final int n = s.length();
    // lcs[i][j] := the number of the same letters of s[i..n) and s[j..n)
    int[][] lcs = new int[n + 1][n + 1];
    // dp[i] := the maximum number of operations needed to delete s[i..n)
    int[] dp = new int[n];
    Arrays.fill(dp, 1);

    for (int i = n - 1; i >= 0; --i)
      for (int j = i + 1; j < n; ++j) {
        if (s.charAt(i) == s.charAt(j))
          lcs[i][j] = lcs[i + 1][j + 1] + 1;
        if (lcs[i][j] >= j - i)
          dp[i] = Math.max(dp[i], dp[j] + 1);
      }

    return dp[0];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def deleteString(self, s: str) -> int:
    n = len(s)
    # lcs[i][j] := the number of the same letters of s[i..n) and s[j..n)
    lcs = [[0] * (n + 1) for _ in range(n + 1)]
    # dp[i] := the maximum number of operations needed to delete s[i..n)
    dp = [1] * n

    for i in reversed(range(n)):
      for j in range(i + 1, n):
        if s[i] == s[j]:
          lcs[i][j] = lcs[i + 1][j + 1] + 1
        if lcs[i][j] >= j - i:
          dp[i] = max(dp[i], dp[j] + 1)

    return dp[0]