JavaScript 中最长递减子序列子数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 17:16:17
我们需要编写一个 JavaScript 函数,该函数接受一个整数数组。该函数应返回数组中最长递减子序列的长度。
例如 −
如果输入数组是 −
const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];
那么输出应该是 −
const output = 4;
因为最长递减子序列(连续单词)是 [5, 4, 3, 2];
示例
const arr = [5, 2, 5, 4, 3, 2, 4, 6, 7];
const decreasingSequence = (arr = []) => {
let longest = [];
let curr = [];
const setDefault = (newItem) => {
if (curr.length > longest.length) { longest = curr;
}
curr = [newItem];
};
for (const item of arr) {
if (curr.length && item > curr[curr.length - 1]) {
setDefault(item);
} else {
curr.push(item);
}
}
setDefault();
return longest.length;
};
console.log(decreasingSequence(arr));
输出
这将产生以下输出 −
4
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

