C++ solution that works for infinite stream


  • 0
    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int ans = 0, prevLen = 0, curLen = 0;
            bool hasZero = false;
            for(int i = 0; i < nums.size(); ++i){
                if(nums[i] == 0){
                    if(i > 0 && nums[i-1] == 0){ // two consecutive zeros, set the prevLen to be zero since we cannot use it anymore
                        prevLen = 0;
                    }else{
                        prevLen = curLen; // update prevLen 
                    }
                    curLen = 0;
                    hasZero = true;
                }else{
                    ++curLen;
                }
                ans = max(ans, prevLen + hasZero + curLen);
            }
            
            return ans;
        }
    };
    

Log in to reply
 

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