From a56758580db98fb3564846bbd61f611d07525239 Mon Sep 17 00:00:00 2001 From: Omkarnath Parida Date: Sun, 4 Oct 2020 01:06:25 +0530 Subject: [PATCH] Optimized the code --- .../LongestCommonSubsequence.js | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/Dynamic-Programming/LongestCommonSubsequence.js b/Dynamic-Programming/LongestCommonSubsequence.js index ac5e61e3a..9ba2edbbb 100644 --- a/Dynamic-Programming/LongestCommonSubsequence.js +++ b/Dynamic-Programming/LongestCommonSubsequence.js @@ -1,31 +1,36 @@ /* - * Given two sequences, find the length of longest subsequence present in both of them. - * A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. + * Given two sequences, find the length of longest subsequence present in both of them. + * A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. * For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg” */ -function longestCommonSubsequence(x, y, str1, str2, dp) { - if (x == -1 || y == -1) return 0; +function longestCommonSubsequence (x, y, str1, str2, dp) { + if (x === -1 || y === -1) { + return 0 + } else { - if (dp[x][y] != 0) return dp[x][y]; + if (dp[x][y] !== 0){ + return dp[x][y] + } else { - if (str1[x] == str2[y]) { - return dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp); + if (str1[x] === str2[y]) { + dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp); + return dp[x][y] } else { - return dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp)) + dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp)) + return dp[x][y] } } } - } -function main() { - const str1 = "ABCDGH" - const str2 = "AEDFHR" +function main () { + const str1 = 'ABCDGH' + const str2 = 'AEDFHR' const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0)) const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp) - console.log(res); + console.log(res) } main()