Maximum length of mountain in an array using JavaScript

JavascriptWeb DevelopmentFront End Technology

Mountain Subsequence

We call any (contiguous) subarray sub (of arr) a mountain if the following properties hold −

  • sub.length >= 3

  • There exists some 0 < i < sub.length - 1 such that sub[0] < sub[1] < ... sub[i-1] < sub[i] > B[i+1] > ... > sub[sub.length - 1]

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 supposed to return the length of the greatest mountain subsequence present in the array arr, if there exists any, 0 otherwise.

For example, if the input to the function is

Input

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

Output

const output = 5;

Output Explanation

Because the desired subarray is −

[2, 5, 8, 4, 3]

Example

Following is the code −

 Live Demo

const arr = [3, 2, 5, 8, 4, 3, 6];
const mountainLength = (arr = []) => {
   let max = 0
   for(let left = 0; left < arr.length; left++) {
      let right = left
      while(arr[right] < arr[right + 1]) {
         right++
      }
      const top = right
      while(right > left && arr[right] > arr[right + 1]) {
         right++
      }
      if(right > top && top > left) {
         max = Math.max(max, right - left + 1)
         left = right
         left--
      }
   }
   return max
}
console.log(mountainLength(arr));

Output

5
raja
Published on 24-Apr-2021 09:50:20
Advertisements