ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของคู่ตัวเลข arr เป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว ในทุกคู่ หมายเลขแรกจะน้อยกว่าหมายเลขที่สองเสมอ
ตอนนี้ เรากำหนดคู่ (c, d) ที่สามารถติดตามคู่อื่น (a, b) ได้ก็ต่อเมื่อ b
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ
ป้อนข้อมูล
const arr = [ [1, 2], [2, 3], [3, 4] ];
ผลผลิต
const output = 2;
คำอธิบายผลลัพธ์
สายที่ยาวที่สุดคือ [1,2] -> [3,4]
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [ [1, 2], [2, 3], [3, 4] ]; const findLongestChain = (arr = []) => { arr.sort(([, b], [, d]) => b - d) let currentEnd = arr[0][1] let count = 1 for (const [start, end] of arr) { if (start > currentEnd) { count += 1 currentEnd = end } } return count } console.log(findLongestChain(arr));
ผลลัพธ์
2