C++ O(n) solution

  • 1

    it uses a sliding window with at most one '0' and then count the window length

    class Solution {
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int start=0, usedup=0, maxl=0;
            for (int i=0; i<nums.size(); ++i) {
                if (nums[i]==0) {
                    if (!usedup) usedup=1;
                    else {
                        while(nums[start] !=0) start++;
                maxl = max(maxl, i-start+1);
            return maxl;

Log in to reply

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