Home > Article > Web Front-end > Get the maximum length of an array using JavaScript
We call any (continuous) subarray sub(arr) a mountain-
sub.length >= 3
There are some 0 B[i 1] > ... > sub[sub.length - 1]
We need to write a JavaScript function that accepts a numeric array arr as the first and only parameter.
Our function should return the length of the largest mountain subsequence that exists in the array arr, or 0 if it exists.
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 required subarray is-
[2, 5, 8, 4, 3]
The following is the code-
Live demonstration
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));
5
The above is the detailed content of Get the maximum length of an array using JavaScript. For more information, please follow other related articles on the PHP Chinese website!