Skip to content

Lis #396

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 4, 2020
Merged

Lis #396

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Dynamic-Programming/LongestCommonSubsequence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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
} else {
if (dp[x][y] !== 0) {
return dp[x][y]
} else {
if (str1[x] === str2[y]) {
dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp)
return dp[x][y]
} else {
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'
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)
}

main()
27 changes: 27 additions & 0 deletions Dynamic-Programming/LongestIncreasingSubsequence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* A Dynamic Programming based solution for calculating Longest Increasing Subsequence
* https://en.wikipedia.org/wiki/Longest_increasing_subsequence
*/

function main () {
const x = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
const length = x.length
const dp = Array(length).fill(1)

let res = 1

for (let i = 0; i < length; i++) {
for (let j = 0; j < i; j++) {
if (x[i] > x[j]) {
dp[i] = Math.max(dp[i], 1 + dp[j])
if (dp[i] > res) {
res = dp[i]
}
}
}
}

console.log('Length of Longest Increasing Subsequence is:', res)
}

main()