เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ไบนารี (อาร์เรย์ที่ประกอบด้วย 0 หรือ 1 เท่านั้น) เป็นอาร์กิวเมนต์เดียว ฟังก์ชันต้องหาความยาวของซับอาร์เรย์ติดต่อกันที่ประกอบด้วย 1 เท่านั้นและคืนค่า
ตัวอย่าง
ถ้าอาร์เรย์นำเข้าคือ:
const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
ผลลัพธ์ควรเป็น:
const output = 4;
เราจะใช้อัลกอริทึมหน้าต่างเลื่อน (sliding window) เพื่อจับหน้าต่างที่ใหญ่ที่สุดที่ประกอบด้วย 1 เท่านั้น
ตัวอย่างโค้ด
const arr = [1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1];
const findMaxConsecutiveOnes = (arr = []) => {
let left = 0;
let right = 0;
let max = 0;
while (right < arr.length) {
if (arr[right] === 0) {
if (right - left > max) {
max = right - left;
}
right++;
left = right;
} else {
right++;
}
}
return right - left > max ? right - left : max;
};
console.log(findMaxConsecutiveOnes(arr));
ผลลัพธ์
4