# 2370. Longest Ideal Subsequence

this DP is similar to LIS, we only care about the tail, so I only save the last char and the freq count

```
T: O(n)
S: O(26)
```

````java
```java
class Solution {
    // 7 1 7 7 8
    // result = 1;
    // map [(1,1), (7, 3), (8, 4)]
    public int longestIdealString(String s, int k) {
        Map<Character, Integer> map = new HashMap<>();
        int result = 0;
        for (char c : s.toCharArray()) { // O(n)
            int count = 0;
            for (Character key : map.keySet()) { // O(26)
                if (Math.abs(key - c) <= k) {
                    count = Math.max(count, map.get(key));
                }
            }
            map.put(c, count+1); // 7, 1
            result = Math.max(result, count+1);
        }
        return result;
    }
}

/**
T: O(n)
S: O(26)


 t subseq in s

 abs(diff) <= k
k = 2


7 1 7 7 8

1_1

1_7

1_8

everytime update larger one



actually can use LIS idea to solve this,
but mine is also ok

這類需要限制在某範圍內的題目...邊掃邊看前面就可以, 不需要前後都看
 */
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/lis/2370.-longest-ideal-subsequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
