All problems

Problem 658

Longest Ideal Subsequence

Medium · 20 pts · String, Dynamic Programming

Problem

A subsequence of S is ideal if every two neighbouring letters in it are at most K apart in the alphabet (for example, a and c are 2 apart). Find the length of the longest ideal subsequence. The alphabet is not cyclic, so a and z are 25 apart. Keep best[c], the longest ideal subsequence so far that ends with letter c; a new letter x extends the best among the letters within K of x.

Input

The first line contains S (lowercase letters). The second line contains K.

Output

Print the length of the longest ideal subsequence.

Constraints

1 <= |S| <= 100000; 0 <= K <= 25

Example input

acfgbd
2

Example output

4

Explanation

For acfgbd with K = 2, the subsequence acbd is ideal: a to c is 2, c to b is 1 and b to d is 2. No longer ideal subsequence exists, so the answer is 4.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Number of Ways to Stay in the Same Place Next: Minimum Falling Path Sum II