Talentd
FleetCode

3472. Longest Palindromic Subsequence After at Most K Operations

Medium38.0% acceptance1 company

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 <= 200
  • 1 <= k <= 200
  • s consists of only lowercase English letters.

Asked at 1 company

Hints open one at a time

Hint 1
Use dynamic programming.
Hint 2
dp[i][j][k] is the length of the longest palindromic subsequence in substring [i..j] with cost at most k.
Hint 3
dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k], dp[i + 1][j - 1][k - dist(s[i], s[j])] + 2), where dist(x, y) is the minimum cyclic distance between x and y.
18:52
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def longestPalindromicSubsequence(self, s: str, k: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"abced"
2
Input
"aaazzz"
4
Your code is saved on this device.Solution