Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Longest decreasing subsequence subarray in JavaScript
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
Advertisements