DEV Community

Joe Avila
Joe Avila

Posted on • Updated on

Max Consecutive Ones (Javascript)

Algorithms have been a struggle for me to learn. I don't particularly enjoy them (until I solve them). I've been told they're an important part of being a developer, especially when searching for your first job. I practice on Leetcode and I'll start posting my accepted submissions here.

Here is my solution for this Leetcode problem.

Given a binary array, find the maximum number of consecutive 1s in this array.

  • The input array will only contain 0 and 1.
  • The length of the input array is a positive integer and will not exceed 10,000

My job is to count the number of times the number 1 appears in a row and return the largest run of 1's. Just from reading the description using a for loop to touch each entry in the array is my plan. I'll use two variables. One to keep track of the current count and the second, the return value, to keep track of the largest number of 1's in a row. I'll call those currentCount and largestCount respectively.

var findMaxConsecutiveOnes = function(nums) {
    let largestCount = 0;
    let currentCount = 0;
    for (let i = 0; i<nums.length; i++) {
        if (nums[i] === 0) {
            currentCount = 0;
        } else {
        if (currentCount > largestCount) largestCount = currentCount;
    return largestCount;
Enter fullscreen mode Exit fullscreen mode

Going through the array:

  • First I check if the element (nums[i]) is 0.
    • If it is 0, I set currentCount to 0. Because that ends any run I have going.
  • If the element is not 0, I add one to currentCount.
    • This works because of the note supplied by Leetcode. The only elements in the array will only be 1 or 0.
  • Before ending the current iteration of the loop, I check and see if the currentCount is greater than the largestCount. If so, set that to largestCount.

After iterating through the entire array return the largestCount.

Here is a refactor of this code using a ternary instead of an if/else statement.

var findMaxConsecutiveOnes = function(nums) {
    let largest = 0;
    let current = 0;
    for (let i = 0; i<nums.length; i++) {
        nums[i] === 0 ? current = 0 : current++;
        if (current > largest) largest = current;
    return largest;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

vital_tech_results profile image
Devadi Dev • Edited

Makes sense. I wonder if this can be done using