JavaScript中的连续1的旋转
问题
我们需要编写一个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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP