JavaScript O(n) time and O(1) space


  • 0
    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 + ones, !!prevOnes * (prevOnes + 1) + ones);
        }
        
        return max;
    };
    

    Track the previous cluster of ones if separated from the current cluster by exactly one zero. hasZero takes care of the case when nums is a single cluster of 1s left-padded by any number of zeroes (including none).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.