topic:
Given a binary array, calculate the maximum number of consecutive 1s.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits and the last three digits are consecutive 1, so the maximum number of consecutive 1s is 3.
Note:The input array contains only 0 and 1.
The length of the input array is a positive integer and does not exceed 10,000.
Ideas:
1. Traverse the array
1) The value is 1, the count is increased by 1
2) Otherwise, the count is cleared
2. After the traversal is over, assign the largest value to max again
Code:
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function(nums) {
let count = 0, max = 0;
for(let i = 0; i < nums.length; i++) {
if(nums[i] === 1) {
count++;
} else {
count > max && (max = count);
count = 0;
}
}
count > max && (max = count);
return max;
};