Total number of longest increasing sequences in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 24-Apr-2021 13:58:05
Advertisements