Maximum Number of Non-overlapping Palindrome Substrings Problem
Description
LeetCode Problem 2472.
You are given a string s and a positive integer k.
Select a set of non-overlapping substrings from the string s that satisfy the following conditions:
- The length of each substring is at least
k. - Each substring is a palindrome.
Return the maximum number of substrings in an optimal selection.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abaccdbbd", k = 3
Output: 2
Explanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3.
It can be shown that we cannot find a selection with more than two valid substrings.
Example 2:
Input: s = "adbcda", k = 2
Output: 0
Explanation: There is no palindrome substring of length at least 2 in the string.
Constraints:
1 <= k <= s.length <= 2000sconsists of lowercase English letters.
Solution
Approach: Palindrome Table + Dynamic Programming
First build g[i][j], which says whether s[i..j] is a palindrome: s[i] == s[j] and the inside g[i+1][j-1] is a palindrome.
Let f[i] be the largest number of non-overlapping palindromes of length at least k we can pick from s[i..], with f[n] = 0. Going from i = n - 1 down to 0, we either skip s[i], giving f[i+1], or start a palindrome at i that ends at some j >= i + k - 1 with g[i][j] true, giving 1 + f[j+1]. Take the best option. The answer is f[0].
Complexity: O(n2) time and O(n2) space, where n is the length of s.
class Solution:
def maxPalindromes(self, s: str, k: int) -> int:
n = len(s)
g = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = s[i] == s[j] and g[i + 1][j - 1]
f = [0] * (n + 1)
for i in range(n - 1, -1, -1):
f[i] = f[i + 1]
for j in range(i + k - 1, n):
if g[i][j]:
f[i] = max(f[i], 1 + f[j + 1])
return f[0]