485. Max Consecutive Ones
Problem
Tags: Array
Given a binary array nums
, return the maximum number of consecutive 1
's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
Constraints:
1 <= nums.length <= 10^5
nums[i]
is either0
or1
.
Code
JS
// 485. Max Consecutive Ones (7/10/53411)
// Runtime: 84 ms (56.37%) Memory: 41.10 MB (94.93%)
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function(nums) {
let max = 0;
for(let i = 0; i < nums.length; i++) {
while (i < nums.length && nums[i] === 0) i++;
let zone_start = i;
while (i < nums.length && nums[i] === 1) i++;
let zone_end = i;
let zone_length = zone_end - zone_start;
max = zone_length > max ? zone_length : max;
}
return max;
};