Longest Palindromic Subsequence After at Most K Operations - Problem

You're given a string s and an integer k. Your goal is to find the longest palindromic subsequence possible after performing at most k character transformations.

In each operation, you can transform any character to its next or previous letter in the alphabet (with wraparound). For example:

  • 'a''b' (next) or 'a''z' (previous)
  • 'z''a' (next) or 'z''y' (previous)
  • 'm''n' (next) or 'm''l' (previous)

Key insight: You need to strategically use your k operations to create the longest possible palindromic subsequence. Remember, a subsequence doesn't need to be contiguous, but it must maintain the original relative order of characters.

Input & Output

example_1.py — Basic transformation
$ Input: s = "abcd", k = 2
Output: 4
💡 Note: We can transform 'a'→'d' (cost: min(3,23)=3 > k) or 'b'→'c' (cost: 1 ≤ k). Better approach: transform 'a'→'b' (cost: 1) and 'd'→'c' (cost: 1), making "bbcc". The longest palindromic subsequence is "bccb" with length 4.
example_2.py — Wraparound case
$ Input: s = "aaa", k = 1
Output: 3
💡 Note: The string is already "aaa", which is itself a palindrome. No operations needed, so the longest palindromic subsequence has length 3.
example_3.py — Limited operations
$ Input: s = "abc", k = 0
Output: 1
💡 Note: With k=0, no transformations are allowed. The original string "abc" has no repeated characters, so the longest palindromic subsequence is any single character, giving length 1.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 0 ≤ k ≤ 1000
  • s consists only of lowercase English letters
  • Time limit: 2 seconds per test case

Visualization

Tap to expand
Longest Palindromic Subsequence After K Operations INPUT String s = "abcd" a i=0 b i=1 c i=2 d i=3 k = 2 Circular Alphabet: a g n z ALGORITHM (DP) 1 Define DP State dp[i][j][ops] = max LPS from i to j with ops left 2 Calculate Cost cost(c1,c2) = min steps to match chars (circular) 3 DP Transitions If cost <= ops: match Else: skip i or j 4 Compute Result Return dp[0][n-1][k] Cost Matrix Example: a b c d d 3 2 1 0 c 2 1 0 1 b 1 0 1 2 FINAL RESULT Optimal Transformation: Original: "abcd" a b c d b +1 op b 0 op b +1 op b +2 op Result: "bbbb" (palindrome) Output: 4 OK - All 4 chars matched! Total ops used: 2 <= k Key Insight: The circular alphabet allows two paths between any characters. The cost to match two chars is min(|c1-c2|, 26-|c1-c2|). Use DP to track remaining operations and maximize palindrome length. For "abcd" with k=2: match (a,d) costs 3, (b,c) costs 1. Total=4 but k=2. Better: transform all to 'b'. TutorialsPoint - Longest Palindromic Subsequence After at Most K Operations | DP Approach
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
28.5K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen