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

山子序列
如果满足以下属性,我们将任何(连续)子数组 sub(arr)称为山 -
-
sub.length >= 3
存在一些 0 < i < sub.length - 1 使得 sub[0] < sub[1] < ... sub[i-1] < sub[i] > 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