Longest Palindromic Subsequence After at Most K Operations Problem
Description
LeetCode Problem 3472.
You are given a string s and an integer k.
In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that 'a' is after 'z'). For example, replacing 'a' with the next letter results in 'b', and replacing 'a' with the previous letter results in 'z'. Similarly, replacing 'z' with the next letter results in 'a', and replacing 'z' with the previous letter results in 'y'.
Return the length of the longest palindromic subsequence of s that can be obtained after performing at most k operations.
Example 1:
Input: s = "abced", k = 2
Output: 3
Explanation:
- Replace s[1] with the next letter, and s becomes "acced".
- Replace s[4] with the previous letter, and s becomes "accec".
The subsequence "ccc" forms a palindrome of length 3, which is the maximum.
Example 2:
Input: s = "aaazzz", k = 4
Output: 6
Explanation:
- Replace s[0] with the previous letter, and s becomes "zaazzz".
- Replace s[4] with the next letter, and s becomes "zaazaz".
- Replace s[3] with the next letter, and s becomes "zaaaaz".
The entire string forms a palindrome of length 6.
Constraints:
1 <= s.length <= 2001 <= k <= 200sconsists of only lowercase English letters.
Solution
Approach: Memoized Search
Let dfs(i, j, k) be the length of the longest palindromic subsequence of s[i..j] when at most k operations may be used. The answer is dfs(0, n - 1, k).
- If
i > j, return 0; ifi == j, return 1. - Skip one end:
dfs(i + 1, j, k)ordfs(i, j - 1, k). - Or match both ends: change one letter into the other, which costs
t = min(d, 26 - d)whered = |s[i] - s[j]|because the alphabet is cyclic. Ift <= k, takedfs(i + 1, j - 1, k - t) + 2.
Return the maximum, caching every state.
Complexity: O(n^2 * k) time and space.
from functools import lru_cache
class Solution:
def longestPalindromicSubsequence(self, s: str, k: int) -> int:
@lru_cache(None)
def dfs(i: int, j: int, k: int) -> int:
if i > j:
return 0
if i == j:
return 1
res = max(dfs(i + 1, j, k), dfs(i, j - 1, k))
d = abs(s[i] - s[j])
t = min(d, 26 - d)
if t <= k:
res = max(res, dfs(i + 1, j - 1, k - t) + 2)
return res
s = list(map(ord, s))
n = len(s)
ans = dfs(0, n - 1, k)
dfs.cache_clear()
return ans