Simple C Solution with easy explanation


  • 13
    S

    Use the fact that multiplication with 0 resets everything..

    int findMaxConsecutiveOnes(int* nums, int numsSize) {
     int max = 0;
     int sum = 0;
     for (int i=0; i<numsSize; i++)
     {
         sum = (sum+nums[i])*nums[i];
         if(max<sum){max=sum;}
     }
    return max;
    }
    

  • 3
    B
    int findMaxConsecutiveOnes(vector<int>& nums) {
         int max = 0;
         int sum = 0;
         for (int i=0; i<nums.size(); i++)
         {
             if(nums[i] == 1)
                sum++;
             else 
                sum = 0;
             if(max<sum)
                max=sum;
         }
        return max;
    }

  • 0
    J

    int findMaxConsecutiveOnes(vector<int>& nums) {
    int count=0,maxcount=0;
    for(int i=0;i<nums.size();i++)
    {
    if(nums[i]==1)count++;
    maxcount=max(maxcount,count);
    if(nums[i]!=1)count=0;
    }
    return maxcount;

    }

Log in to reply
 

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