mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Added Longest Increasing Subsequence program to the list
This commit is contained in:
26
Dynamic-Programming/LongestIncreasingSubsequence.js
Normal file
26
Dynamic-Programming/LongestIncreasingSubsequence.js
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 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()
|
Reference in New Issue
Block a user