Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 04:54
Show Gist options
  • Save pjcodesjs/452f70f5fd9418b91474b99ccb83f13b to your computer and use it in GitHub Desktop.
Save pjcodesjs/452f70f5fd9418b91474b99ccb83f13b to your computer and use it in GitHub Desktop.
function longestConsecutiveSubsequence(arr) {
arr.sort((a, b) => a - b); // Step 1
let longestSubsequence = 1; // Step 2
let currentSubsequence = 1; // Step 3
for (let i = 1; i < arr.length; i++) { // Step 4
if (arr[i] === arr[i - 1] + 1) { // Step 5
currentSubsequence++;
if (currentSubsequence > longestSubsequence) { // Step 6
longestSubsequence = currentSubsequence;
}
} else { // Step 7
currentSubsequence = 1;
}
}
return longestSubsequence; // Step 8
}
const arr = [1, 2, 3, 5, 6, 7, 9, 10, 11];
console.log(longestConsecutiveSubsequence(arr)); // Output: 3 (because the longest consecutive subsequence is 9, 10, 11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment