Home > Web Front-end > JS Tutorial > body text

Get the maximum length of an array using JavaScript

WBOY
Release: 2023-08-24 12:25:08
forward
484 people have browsed it

使用 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];
Copy after login

output

const output = 5;
Copy after login

Output explanation

Because the required subarray is-

[2, 5, 8, 4, 3]
Copy after login

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));
Copy after login

Output

5
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!