Given a string s of lowercase letters and an integer k, choose exactly k substrings of s so that every chosen substring is a palindrome and no two chosen substrings overlap in their positions within s. Return the largest possible total length of the chosen substrings. If it is not possible to choose k such substrings, return 0.
Function Signature
def max_palindromic_total_length(s: str, k: int) -> int:
Rules
-
A substring is a contiguous block of characters. A palindrome reads the same forward and backward, so every single character is a palindrome.
-
Two chosen substrings may sit next to each other, but they may not share an index.
-
Exactly
k
substrings must be chosen. Characters that belong to no chosen substring are allowed.
-
Return
0
when no valid choice exists. Under the constraints below this never happens, because
k
single characters are always a valid choice.
Constraints
-
1 <= len(s) <= 200
-
1 <= k <= len(s)
-
s
consists of lowercase English letters.
Examples
Input: s = "abaccdbbd", k = 2
Output: 7
Choose "aba" (indices 0 to 2) and "dbbd" (indices 5 to 8) for a total of 3 + 4 = 7. The only palindrome of length 4 in the string is "dbbd" and none is longer, so two pieces cannot cover more than 4 + 3 characters.
Input: s = "aab", k = 2
Output: 3
Choose "aa" and "b". Together they cover every character of the string, so no choice can do better.
Input: s = "aba", k = 2
Output: 2
The whole string "aba" is a palindrome, but choosing it leaves no room for a second piece. The best valid choice is two single letters, such as "a" and "b".