3472. Longest Palindromic Subsequence After at Most K Operations
3472. Longest Palindromic Subsequence After at Most K Operations
Description
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:
1 | Input: s = "abced", k = 2 |
Explanation:
- Replace
s[1]
with the next letter, ands
becomes"acced"
. - Replace
s[4]
with the previous letter, ands
becomes"accec"
.
The subsequence "ccc"
forms a palindrome of length 3, which is the maximum.
Example 2:
1 | Input: s = "aaazzz", k = 4 |
Explanation:
- Replace
s[0]
with the previous letter, ands
becomes"zaazzz"
. - Replace
s[4]
with the next letter, ands
becomes"zaazaz"
. - Replace
s[3]
with the next letter, ands
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.
Hints/Notes
- 2025/03/01 Q1
- dp
- 0x3Fâs solution
- Weekly Contest 439
Solution
Language: C++
1 | class Solution { |