Skip to content

Commit 9934128

Browse files
authored
* Added Longest Common Subsequence * Renamed the File * Optimized the code * Optimized the code * Changed some styles as per the rule * Again some style fixed * Added Longest Increasing Subsequence program to the list * Style changed
1 parent c947571 commit 9934128

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Given two sequences, find the length of longest subsequence present in both of them.
3+
* A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
4+
* For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”
5+
*/
6+
7+
function longestCommonSubsequence (x, y, str1, str2, dp) {
8+
if (x === -1 || y === -1) {
9+
return 0
10+
} else {
11+
if (dp[x][y] !== 0) {
12+
return dp[x][y]
13+
} else {
14+
if (str1[x] === str2[y]) {
15+
dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp)
16+
return dp[x][y]
17+
} else {
18+
dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp))
19+
return dp[x][y]
20+
}
21+
}
22+
}
23+
}
24+
25+
function main () {
26+
const str1 = 'ABCDGH'
27+
const str2 = 'AEDFHR'
28+
const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
29+
const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
30+
console.log(res)
31+
}
32+
33+
main()
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* A Dynamic Programming based solution for calculating Longest Increasing Subsequence
3+
* https://en.wikipedia.org/wiki/Longest_increasing_subsequence
4+
*/
5+
6+
function main () {
7+
const x = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
8+
const length = x.length
9+
const dp = Array(length).fill(1)
10+
11+
let res = 1
12+
13+
for (let i = 0; i < length; i++) {
14+
for (let j = 0; j < i; j++) {
15+
if (x[i] > x[j]) {
16+
dp[i] = Math.max(dp[i], 1 + dp[j])
17+
if (dp[i] > res) {
18+
res = dp[i]
19+
}
20+
}
21+
}
22+
}
23+
24+
console.log('Length of Longest Increasing Subsequence is:', res)
25+
}
26+
27+
main()

0 commit comments

Comments
 (0)