LeetCode Problem - Link


introduced in the Arrays 101 track of LeetCode. I first solved this and got it wrong by over-complicating it. Deleted the whole code and tried a simpler approach.


Simple Iterative Approach

If we encounter a 1, increment counter - check if its the highest value, update our max counter if it is, else ignore.

By the end of the array, our consecutive 1s count will be updated in our max count value which we return

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function(nums) {
    var counter = 0;
    var max_counter = 0;
    
    for(var i=0;i<nums.length;i++){
        if(nums[i]==1){
            counter+=1
        }else{
            counter = 0;
        }
        
        if(counter>max_counter){
            max_counter = counter
        }
    }
    return max_counter
};