Longest Ideal Subsequence

Medium Topics Company Tags

Choose a subsequence of s such that adjacent chosen letters differ by at most k positions in the alphabet. Return the greatest possible length. A subsequence preserves the original order but may skip characters.

Alphabet distance does not wrap around: the distance from a to z is 25.

Example 1:

Input: s = "azaz"
k = 0

Output: 2

Explanation: When k is zero, adjacent chosen letters must be equal. Choosing either the two a characters or the two z characters gives length 2.

Example 2:

Input: s = "bdac"
k = 1

Output: 2

Explanation: A subsequence such as "ba" or "dc" has length 2 and adjacent distance 1. No three characters in their original order satisfy the distance limit.

Example 3:

Input: s = "az"
k = 25

Output: 2

Explanation: With k = 25, a and z may be adjacent. Keeping both characters gives length 2.

Constraints:

  • 1 <= s.length <= 100000
  • s contains only lowercase English letters.
  • 0 <= k <= 25


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.