

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Valid Mountain Array in Python
- Longest Mountain in Array in C++
- Maximum length product of unique words in JavaScript
- Finding maximum length of common subarray in JavaScript
- JavaScript - length of array objects
- How to find the length of an array in JavaScript?
- Maximum average of a specific length of subarray in JavaScript
- Length of a JavaScript associative array?
- Length of shortest unsorted array in JavaScript
- Finding even length numbers from an array in JavaScript
- JavaScript Array length property
- How to find the maximum value of an array in JavaScript?
- Maximum subarray sum in circular array using JavaScript
- How to find maximum value in an array using spread operator in JavaScript?
- Maximum Length Chain of Pairs
Advertisements