find the longest sorted sequence in a list of numbers in javascript

index.tsx
function findLongestSequence(arr) {
  let longestSequence = [];
  let currentSequence = [arr[0]];

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] >= arr[i-1]) {
      currentSequence.push(arr[i]);
    } else {
      if (currentSequence.length > longestSequence.length) {
        longestSequence = currentSequence;
      }
      currentSequence = [arr[i]];
    }
  }

  if (currentSequence.length > longestSequence.length) {
    longestSequence = currentSequence;
  }

  return longestSequence;
}

// Example usage:
const arr = [1, 3, 5, 3, 4, 7, 8, 9, 2, 4, 6, 8];
const longestSequence = findLongestSequence(arr);
console.log(longestSequence); // Output: [2, 4, 6, 8]
678 chars
27 lines

The findLongestSequence function takes an array of numbers as input and returns the longest sorted sequence found in the input array. It creates two arrays, longestSequence and currentSequence, and uses a for loop to iterate through the input array. If the current number is greater than or equal to the previous number, it adds the current number to the currentSequence array. If the current number is less than the previous number, it checks if the currentSequence array is longer than the longestSequence array, and if it is, it updates the longestSequence array to be the currentSequence array. At the end of the loop, it checks one last time if the currentSequence array is longer than the longestSequence array, and if it is, updates longestSequence to be currentSequence. Finally, it returns the longestSequence array.

gistlibby LogSnag