Home  >  Article  >  Web Front-end  >  Get the maximum length of an array using JavaScript

Get the maximum length of an array using JavaScript

WBOY
WBOYforward
2023-08-24 12:25:08529browse

使用 JavaScript 获取数组中山的最大长度

山subsequence

We call any (continuous) subarray sub(arr) a mountain-

    if it satisfies the following properties
  • sub.length >= 3

  • There are some 0 B[i 1] > ... > sub[sub.length - 1]

Question

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]

Example

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));

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete