Max Consecutive Ones | JavaScript | LeetCode

Max Consecutive Ones | JavaScript | LeetCode

Leetcode Array Problems | Arrays 101

First, we will take a look at the problem statement, Given a binary array nums, return the maximum number of consecutive 1's in the array.

Now take a look at the constraints:

1 <= nums.length <= 10<sup>5</sup>

This means that the array nums can have at least 1 element and at most 100,000 elements.

nums[i] is either 0 or 1

This means each element in the array nums is either 0 or 1. The array is a binary array, containing only two possible values

Now let us see the solution (JavaScript)

var findMaxConsecutiveOnes = function(nums) {
    let maxCount = 0;
    let count = 0;
        for(let num of nums) {
        if(num === 1) {
            count++;
        } else {
           maxCount = Math.max(maxCount, count);
           count = 0; 
        }
    }
    return Math.max(maxCount, count);
};

If the current element (num) is 1, the count is incremented.

If the current element is not 1 (i.e., it is 0), the current sequence of 1's ends. The maxCount is updated to the maximum of maxCount and count, and then count is reset to 0.

In conclusion, always start by trying to solve problems on your own. Once you've given it your best effort, seek the best solutions.