Today I have solved the problem in javascript
Describe an algorithm to compute the longest increasing subsequence of an array of numbers in O(n log n) time.
const array = [10, 22, 9, 33, 21, 50, 41, 60, 80];
const lis = longestIncreasingSubsequence(array);
function longestIncreasingSubsequence(arr) {
const piles = [];
arr.forEach((num) => {
let pileIndex = binarySearch(piles, num);
if (pileIndex === piles.length) {
piles.push([num]);
} else {
piles[pileIndex].push(num);
} });
return piles.reduce((maxPile, currentPile) => (currentPile.length > maxPile.length ? currentPile : maxPile), []);}
function binarySearch(piles, num) {
let low = 0;
let high = piles.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (piles[mid][piles[mid].length - 1] < num) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
console.log(lis);
.png)
Comments
Post a Comment