Created
November 3, 2018 09:36
-
-
Save queckezz/aa652ccf76dd0aafbef75eb3f07e8804 to your computer and use it in GitHub Desktop.
longest increasing subsequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function longestIncreasingSubsequence(arr) { | |
return arr.slice(0, arr.lastIndexOf(-1)).reduce( | |
(acc, val) => { | |
if (acc.prev == null) { | |
return { ...acc, prev: val } | |
} | |
if (val > acc.prev) { | |
return { ...acc, count: acc.count + 1, prev: val } | |
} else { | |
if (acc.count > acc.largestSequence) { | |
return { count: 1, prev: val, largestSequence: acc.count } | |
} | |
return { ...acc, prev: val, count: 1 } | |
} | |
}, | |
{ | |
count: 1, | |
largestSequence: 1 | |
} | |
) | |
} | |
const input = [22, 35, 4, 16, 42, 3, -1] | |
console.log(input) | |
const x = longestIncreasingSubsequence(input) | |
console.log(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment