首頁  >  文章  >  web前端  >  使用 JavaScript 取得數組中山的最大長度

使用 JavaScript 取得數組中山的最大長度

WBOY
WBOY轉載
2023-08-24 12:25:08469瀏覽

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

山子序列

如果滿足以下屬性,我們將任何(連續)子數組sub(arr)稱為山-

  • sub.length >= 3

  • 存在一些0 B[i 1] > ... > sub[sub.length - 1]

問題

我們需要寫一個JavaScript 函數,該函數接受數字陣列arr 作為第一個也是唯一的參數。

我們的函數應該傳回最大山子序列的長度存在於陣列arr中,如果存在,則為0。

例如,如果函數的輸入為

輸入

const arr = [3, 2, 5, 8, 4, 3, 6];

輸出

const output = 5;

輸出解釋

因為所需的子陣列是-

[2, 5, 8, 4, 3]

範例

以下是程式碼-

## 即時示範

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

以上是使用 JavaScript 取得數組中山的最大長度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除