[front end algorithm] the maximum number of consecutive 1, a traversal

Time:2021-6-9

Given a binary array, calculate the maximum number of consecutive 1.

Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: the first two digits and the last three digits are consecutive ones, so the maximum number of consecutive ones is 3

be careful:

  • The input array contains only 0 and 1.
  • The length of the input array is a positive integer and does not exceed 10000.

Problem solving code

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function(nums) {
    let count = 0;
    let i = 0;
    let result = [];
    while (i < nums.length) {
        if (nums[i] === 1) count++;
        if (nums[i] !== 1) count = 0;
        result.push(count)
        i++;
    }
    return Math.max(...result)
};

[front end algorithm] the maximum number of consecutive 1, a traversal

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]