JavaScript 中具有单位差异的最长子数组
问题
我们需要编写一个JavaScript函数,它接受一个数字数组arr作为第一个也是唯一的参数
我们的函数应该找到并返回这样一个子数组的长度,它的最大值和最小值之间的差正好是1。
例如,如果函数的输入是-
const arr = [2, 4, 3, 3, 6, 3, 4, 8];
那么输出应该是-
const output = 5;
输出说明
因为想要的子数组是[4,3,3,3,4]
示例
以下是代码-
const arr = [2, 4, 3, 3, 6, 3, 4, 8];
const longestSequence = (arr = []) => {
const map = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {})
return Object.keys(map).reduce((max, key) => {
const nextKey = parseInt(key, 10) + 1
if (map[nextKey] >= 0) {
return Math.max(
max,
map[key] + map[nextKey],
)
}
return max
}, 0);
};
console.log(longestSequence(arr));输出结果以下是控制台输出-
5