DEV Community

Karleb
Karleb

Posted on

#2370. Longest Ideal Subsequence

https://leetcode.com/problems/longest-ideal-subsequence/?envType=daily-question&envId=2024-04-25

var longestIdealString = function(s, k) {
    let dp = new Array(27).fill(0);

    for (let i = 0; i < s.length; i++) {
        let diff = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
        let maxi = Number.MIN_SAFE_INTEGER;

        let left = Math.max(diff - k, 0);
        let right = Math.min(diff + k, 26);

        for (let j = left; j <= right; j++) {
            maxi = Math.max(maxi, dp[j]);
        }

        dp[diff] = maxi + 1;
    }

    let max = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < 27; i++) {
        if (dp[i] > max)
            max = dp[i];
    }

    return max;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)