Algorithm Practice: Max Consecutive Ones II

Problem

Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.

Solutions

var findMaxConsecutiveOnes = function(nums) {
let max = 0;
for (let left = 0; left < nums.length; left++) {
let zeroCount = 0;
for(let right = left; right < nums.length; right++) {
if (nums[right] === 0) {
zeroCount++;
}
if (zeroCount <= 1) {
max = Math.max(max, right - left + 1);
} else break;
}

}
return max;
};
var findMaxConsecutiveOnes = function(nums) {
let ones = 0, prevOnes = 0;
let zeroes = 0, hasZero = false;
let max = 0;

for (let k of nums) {
if (k) {
ones++;
zeroes = 0;
} else {
hasZero = true;
prevOnes = (++zeroes === 1) ? ones : 0;
ones = 0;
}
max = Math.max(max, hasZero * prevOnes + hasZero + ones);
}
return max;
};

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store