Skip to content

Instantly share code, notes, and snippets.

@diurivj
Created July 18, 2025 21:53
Show Gist options
  • Select an option

  • Save diurivj/e91d47b081850f8e3deed682da195a7c to your computer and use it in GitHub Desktop.

Select an option

Save diurivj/e91d47b081850f8e3deed682da195a7c to your computer and use it in GitHub Desktop.
const input = [
9, 44, 32, 12, 7, 45, 31, 98, 35, 41, 8, 20, 27, 32, 83, 64, 61, 28, 39, 93,
29, 92, 17,
];
function solution(arr) {
const length = arr.length;
if (!length) return { sequence: [], removed: 0 };
const longest = new Array(length).fill(1);
const previous = new Array(length).fill(-1);
for (let i = 1; i < length; i++) {
for (let j = 0; j < i; j++) {
if (arr[j] < arr[i] && longest[j] + 1 > longest[i]) {
longest[i] = longest[j] + 1;
previous[i] = j;
}
}
}
let maxLength = 0;
let maxIndex = 0;
for (let i = 0; i < length; i++) {
if (longest[i] > maxLength) {
maxLength = longest[i];
maxIndex = i;
}
}
// Here we already know what is the amount of removed elements: length - maxLength
const removed = length - maxLength;
const sequence = [];
let currIndex = maxIndex;
while (currIndex !== -1) {
sequence.unshift(arr[currIndex]);
currIndex = previous[currIndex];
}
return { sequence, removed };
}
const result = solution(input);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment