Problem Description
Given a string s and an integer k, find the length of the longest subsequence of s (called an "ideal" subsequence) such that the absolute difference between every two adjacent characters (in terms of their positions in the alphabet) is at most k.
Key Insights
- We need to compute the longest subsequence that adheres to the constraint on adjacent character differences.
- A dynamic programming approach works well since each character in s can be used to extend the ideal subsequence if its previous character is within k distance in the alphabet.
- Maintain a DP array of size 26 where each entry represents the length of the longest ideal subsequence ending with the corresponding character.
- For every new character, check all characters in the valid range (within k distance) and update the DP value.
- Because there are only 26 letters and k is at most 25, iterating through a constant range yields an efficient solution.
Space and Time Complexity
Time Complexity: O(n * 26) ≈ O(n) (since k and 26 are constant factors) Space Complexity: O(26) which is O(1)
Solution
The solution uses dynamic programming with a one-dimensional array dp of size 26. Each index i in the array represents the maximum length of an ideal subsequence ending with the letter corresponding to i (i.e. 'a' + i). For each character in the string s:
- Convert the character to its index.
- Determine the lower and upper bounds for acceptable previous characters (taking into account k).
- Find the maximum dp value in that range.
- Update dp[current index] with maximum value + 1. Finally, return the maximum value from the dp array, which represents the length of the longest ideal subsequence.