JavaScript 中连续 1 的变体
javascriptweb developmentfront end technology
问题
我们需要编写一个 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