C++ O(N) runtime O(1) space single pass


  • 0
    G
    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int count = 0;
            int maxCount = 0;
            int ConsecOnes = 0;
            bool prevSwapped = false;
            
            for(int i = 0; i <= nums.size(); ++i){
                if(i == nums.size()){
                    maxCount = max(maxCount,count);
                }
                else{
                    if(nums[i] == 0){
                        if(prevSwapped){
                            maxCount = max(maxCount,count);
                            count = ConsecOnes + 1;
                            ConsecOnes = 0;
                        }
                        else{
                            prevSwapped = true;
                            ConsecOnes = 0;
                            count++;
                        }
                    }
                    else{
                        ConsecOnes++;
                        count++;
                    }
                }
            }
            return maxCount;
        }
    };
    

Log in to reply
 

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