
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
Maximum Length of Mountain in an Array Using JavaScript
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 −
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
Advertisements