C++ O(n) solution


  • 1
    L

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

    class Solution {
    public:
        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++;
                        ++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.