Skip to content

Instantly share code, notes, and snippets.

@queckezz
Created November 3, 2018 09:36
Show Gist options
  • Save queckezz/aa652ccf76dd0aafbef75eb3f07e8804 to your computer and use it in GitHub Desktop.
Save queckezz/aa652ccf76dd0aafbef75eb3f07e8804 to your computer and use it in GitHub Desktop.
longest increasing subsequence
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