Longest Ideal String

medium dp string

Problem

You are given a string s of lowercase letters and an integer k. A subsequence of s is called ideal if every pair of adjacent characters in it sits at most k positions apart in the alphabet (no wraparound, so 'a' and 'z' are 25 apart). Return the length of the longest ideal subsequence.

Inputs = "acfgbd", k = 2
Output4
"acbd" is ideal: the adjacent alphabet gaps are 2, 1 and 2, all within k = 2, and no longer ideal subsequence exists.

def longest_ideal_string(s, k):
    dp = [0] * 26   # dp[c] = longest ideal subsequence ending with letter c
    for ch in s:
        c = ord(ch) - ord('a')
        lo = max(0, c - k)
        hi = min(25, c + k)
        best = 0
        for j in range(lo, hi + 1):
            best = max(best, dp[j])
        dp[c] = best + 1
    return max(dp)
function longestIdealString(s, k) {
  const dp = new Array(26).fill(0); // dp[c] = best ending with letter c
  for (const ch of s) {
    const c = ch.charCodeAt(0) - 97;
    const lo = Math.max(0, c - k);
    const hi = Math.min(25, c + k);
    let best = 0;
    for (let j = lo; j <= hi; j++) best = Math.max(best, dp[j]);
    dp[c] = best + 1;
  }
  return Math.max.apply(null, dp);
}
int longestIdealString(String s, int k) {
    int[] dp = new int[26]; // dp[c] = best ending with letter c
    for (char ch : s.toCharArray()) {
        int c = ch - 'a';
        int lo = Math.max(0, c - k);
        int hi = Math.min(25, c + k);
        int best = 0;
        for (int j = lo; j <= hi; j++) best = Math.max(best, dp[j]);
        dp[c] = best + 1;
    }
    int ans = 0;
    for (int v : dp) ans = Math.max(ans, v);
    return ans;
}
int longestIdealString(string s, int k) {
    vector<int> dp(26, 0); // dp[c] = best ending with letter c
    for (char ch : s) {
        int c = ch - 'a';
        int lo = max(0, c - k);
        int hi = min(25, c + k);
        int best = 0;
        for (int j = lo; j <= hi; j++) best = max(best, dp[j]);
        dp[c] = best + 1;
    }
    return *max_element(dp.begin(), dp.end());
}
Time: O(n · k) Space: O(26)