使用 JavaScript 的数组中山的最大长度
山地序列
如果以下属性成立,我们将任何(连续的)子数组子(arr)称为山-
子长度>=3
存在一些0B[i+1]>...>sub[sub.长度-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