'Finding max consecutive 1 in a given array (leetcode)?

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int ctr = 0, max = 0;
        for(int i=0; i<nums.size(); i++){
            if(nums[i]==1)
                    ctr++;
            if(nums[i] == 0 || i == (nums.size()-1))
                if(ctr > max){
                    max = ctr;
                    ctr = 0;
                }
        }
        if(max == 0)
            max = ctr;
        return max;
    }
};

this is my code and it is failing half test cases idk why? i am counting the number of 1's and if the element is zero then i am checking whether it is greater than max and storing it and if it is the end of array then check whether ctr is still greater and store it.



Solution 1:[1]

In this if statement

        if(nums[i] == 0 || i == (nums.size()-1))
            if(ctr > max){
                max = ctr;
                ctr = 0;
            }

you have to set the variable ctr to 0 independent on whether ctr is greater than max. For example

        if(nums[i] == 0 || i == (nums.size()-1))
        {
            if(ctr > max){
                max = ctr;
            }
            ctr = 0;
        }

Also if the vector can contain other numbers apart from 0 and 1 then it will be safer to write the if statement like

        if(nums[i] != 1 || i == (nums.size()-1))

Pay attention to that this code snippet after the for loop

    if(max == 0)
        max = ctr;

is redundant and may be removed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1