Longest decreasing subsequence subarray in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Integers. The function should return the length of the longest decreasing subsequence from the array.

For example −

If the input array is −

const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];

Then the output should be −

const output = 4;

because the longest decreasing subsequence (of consecutive words) is [5, 4, 3, 2];

Example

const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];
const decreasingSequence = (arr = []) => {
   let longest = [];
   let curr = [];
   const setDefault = (newItem) => {
      if (curr.length > longest.length) { longest = curr;
   }
   curr = [newItem];
};
for (const item of arr) {
   if (curr.length && item > curr[curr.length - 1]) {
      setDefault(item);
   } else {
      curr.push(item);
   }
}
setDefault();
   return longest.length;
};
console.log(decreasingSequence(arr));

Output

This will produce the following output −

4
raja
Published on 25-Nov-2020 04:53:35
Advertisements