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
Understanding the Visualization
1
Identify potential pairs
Look at characters from both ends that could form palindromic pairs
2
Calculate transformation costs
For each pair, find the minimum operations needed to make them identical
3
Choose optimal strategy
Decide whether to transform pairs or skip characters based on operation budget
4
Build longest palindrome
Construct the longest possible palindromic subsequence within constraints
Key Takeaway
🎯 Key Insight: Calculate minimum circular alphabet distance between character pairs and use dynamic programming to find the optimal combination of transformations within the operation budget.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code