ปัญหา
เราต้องเขียนฟังก์ชัน 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