Max Consecutive Ones II - C++ - O(N) time and O(1) space

I think this could be written more simply, but we use a sliding window here.

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums)
    {
        // NOTE: Not my best work, but this is O(N) time and O(1) space.
        // The idea is we keep a count of what we've seen, when we reach
        // a second '0', we reset the window and start at the *previous* 0.
        // K points to the *previous* 0. We count the *previous* 0 too because
        // that's the one we could ostensibly flip to a 1.

        int zeroCount = 0;
        int numCount = 0;
        int ret = 0;
        int k = 0;
        for (int i = 0; i < nums.size(); )
        {
            ++numCount;            
            if (nums[i] == 0)
            {
                ++zeroCount;
                if (zeroCount == 1)
                {
                    k = i; // We will start back here if we reach a second 0.
                }
                else
                {
                    if (numCount > ret)
                        ret = numCount - 1; // Don't count the zero accidentally.
                    
                    i = k + 1; // Go backwards!
                    numCount = 0;
                    zeroCount = 0;

                    continue;
                }
            }
            
            ++i;
        }

        // This handles scenarios like [0,1,1,1,1,1,1,1] - here the answer is '8',
        // but when we exited from the loop, we never found a second 0. So just return the count.
        return max(numCount, ret);
    }
};
Comments (0)