
山子序列
如果满足以下属性,我们将任何(连续)子数组 sub(arr)称为山 -
-
sub.length >= 3
存在一些 0 B[i+1] > ... > sub[sub.length - 1]
问题
我们需要编写一个 JavaScript 函数,该函数接受数字数组 arr 作为第一个也是唯一的参数。
立即学习“Java免费学习笔记(深入)”;
我们的函数应该返回最大山子序列的长度存在于数组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










