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
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

้€™้กž้œ€่ฆ้™ๅˆถๅœจๆŸ็ฏ„ๅœๅ…ง็š„้กŒ็›ฎ...้‚ŠๆŽƒ้‚Š็œ‹ๅ‰้ขๅฐฑๅฏไปฅ, ไธ้œ€่ฆๅ‰ๅพŒ้ƒฝ็œ‹
 */
```

Last updated