Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาโซ่คู่ที่ต่อเนื่องกันยาวที่สุดใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของคู่ตัวเลข arr เป็นอาร์กิวเมนต์เดียว ในทุกคู่ ตัวเลขตัวแรกจะน้อยกว่าตัวที่สองเสมอ

ตอนนี้เรากำหนดคู่ (c, d) ว่าสามารถตามหลังคู่ (a, b) ได้ก็ต่อเมื่อ b < c โซ่ของคู่สามารถสร้างได้ในลักษณะนี้ ฟังก์ชันควรหาความยาวโซ่ที่ยาวที่สุดที่สร้างได้

ตัวอย่างเช่น หากอินพุตคือ

Input

const arr = [ 
  [1, 2], [2, 3], [3, 4] ];

Output

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