我们需要编写一个 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