- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Total number of longest increasing sequences in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.
Our function is required to find the number of longest increasing subsequences (contiguous or non-contiguous).
For example, if the input to the function is
Input
const arr = [2, 4, 6, 5, 8];
Output
const output = 2;
Output Explanation
The two longest increasing subsequences are [2, 4, 5, 8] and [2, 4, 6, 8].
Example
Following is the code −
const arr = [2, 4, 6, 5, 8]; const countSequence = (arr) => { const distance = new Array(arr.length).fill(1).map(() => 1) const count = new Array(arr.length).fill(1).map(() => 1) let max = 1 for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[j] > arr[i]) { if (distance[j] <= distance[i]) { distance[j] = distance[i] + 1 count[j] = count[i] max = Math.max(distance[j], max) } else if (distance[j] === distance[i] + 1) { count[j] += count[i] } } } } return distance.reduce((acc, d, index) => { if (d === max) { acc += count[index] } return acc }, 0) } console.log(countSequence(arr));
Output
2
Advertisements