Simple O(n) C++ Solution


  • 0
    M

    Just counted the 1s and found the max such subarray, that is the maximum number of 1s in this array!
    Store the max number of 1s in a "currmax" variable. Now keep counting consecutive 1s, and increment temp.
    Whenever temp is more than currmax, update currmax. When you encounter a 0, reset the value of temp, and start counting next set of consecutive 1s.

    int findMaxConsecutiveOnes(vector<int>& nums) {
            int currmax=0;
            int temp=0;
            for(int i=0;i<nums.size();i++)
            {
                if(nums[i]==1)
                {
                    temp++;
                    if(temp>currmax)
                        currmax=temp;
                }
                else
                    temp=0;
            }
            return currmax;
        }
    

Log in to reply
 

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