Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Total number of longest increasing sequences in JavaScript
Finding the total number of longest increasing subsequences (LIS) is a dynamic programming problem. We need to find all subsequences with the maximum possible length where each element is greater than the previous one.
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:
const arr = [2, 4, 6, 5, 8];
The output should be:
2
Output Explanation
The two longest increasing subsequences are [2, 4, 5, 8] and [2, 4, 6, 8], both having length 4.
Algorithm Explanation
We use dynamic programming with two arrays:
- distance[] - stores the length of the longest increasing subsequence ending at each index
- count[] - stores the number of such subsequences ending at each index
Example
const arr = [2, 4, 6, 5, 8];
const countSequence = (arr) => {
const distance = new Array(arr.length).fill(1);
const count = new Array(arr.length).fill(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));
console.log("Maximum LIS length:", Math.max(...[1, 4, 4, 3, 4])); // 4
2 Maximum LIS length: 4
Step-by-Step Execution
For array [2, 4, 6, 5, 8]:
| Index | Element | Distance (LIS length) | Count |
|---|---|---|---|
| 0 | 2 | 1 | 1 |
| 1 | 4 | 2 | 1 |
| 2 | 6 | 3 | 1 |
| 3 | 5 | 3 | 1 |
| 4 | 8 | 4 | 2 |
Another Example
// Test with different array
const arr2 = [1, 3, 6, 7, 9, 4, 10, 5, 6];
console.log("Array:", arr2);
console.log("Number of LIS:", countSequence(arr2));
Array: [ 1, 3, 6, 7, 9, 4, 10, 5, 6 ] Number of LIS: 2
Time and Space Complexity
- Time Complexity: O(n²) where n is the array length
- Space Complexity: O(n) for the distance and count arrays
Conclusion
This dynamic programming approach efficiently finds the count of longest increasing subsequences by tracking both the length and count of subsequences ending at each position. The algorithm handles overlapping subproblems by building solutions incrementally.
