我们需要编写一个JavaScript函数,该函数接受二进制数组(仅包含0和1的数组)arr作为唯一参数。如果我们最多可以翻转一个0,则我们的函数应该找到此数组中连续1的最大数目。
例如,如果函数的输入为-
const arr = [1, 0, 1, 1, 0];
那么输出应该是-
const output = 4;
如果在数组的索引1处翻转0,我们将得到4个连续的1。
为此的代码将是-
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));输出结果控制台中的输出将是-
4