#1143. Longest Common Subsequence

ยท

1 min read

https://leetcode.com/problems/longest-common-subsequence/description/?envType=daily-question&envId=2024-01-25

function longestCommonSubsequence(text1, text2) {

    const m = text1.length
    const n = text2.length

    const memo = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));

    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {

            if (text1[i - 1] === text2[j - 1]) {
                memo[i][j] = memo[i - 1][j - 1] + 1;
            } else {
                memo[i][j] = Math.max(memo[i - 1][j], memo[i][j - 1]);
            }


        }
    }

    return memo[m][n];
}

Dynamic programming still kicking my ass.

ย