ปัญหา
รับอาร์เรย์ไบนารี หา 1 ต่อเนื่องมากสุด หากอนุญาตให้พลิก 0 เป็น 1 ได้สูงสุด 1 ตัว
ตัวอย่าง
const arr = [1, 0, 1, 1, 0];
พลิก 0 ตำแหน่ง 1 → 1,1,1,1,0 → 4 ตัวติดกัน → 4
โค้ดตัวอย่าง (Sliding Window)
const arr = [1, 0, 1, 1, 0];
const findMaximumOne = (nums = []) => {
let count = 0, first = -1, i = 0, j = 0, res = -Infinity;
while(j < nums.length){
if(nums[j] === 1){ res = Math.max(res, j - i + 1); }
else { count++; if(count == 2){ i = first + 1; count--; } first = j; }
j++;
}
return res;
};
console.log(findMaximumOne(arr));
ผลลัพธ์
4