Vấn đề
Cần viết hàm JS nhận mảng nhị phân arr, tìm số lượng 1 liên tiếp nhiều nhất nếu được phép lật tối đa một 0.
Ví dụ:
const arr = [1, 0, 1, 1, 0];
Kết quả:
const output = 4;
Giải thích:
Lật 0 tại index 1 -> 4 số 1 liên tiếp.
Ví dụ
Mã thực hiện:
const arr = [1, 0, 1, 1, 0]; const findMaximumOne = (nums = []) => { let count = 0; let first = -1; let i =0, j = 0; let 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));
Kết quả
Kết quả in ra console:
4