따봉도치야 고마워

[LeetCode] Arrays 101: Max Consecutive Ones 본문

프로그래밍/알고리즘

[LeetCode] Arrays 101: Max Consecutive Ones

따봉도치 2022. 4. 5. 21:02

문제

이진 배열이 주어지면 배열에서 1이 최대로 연속되는 수를 반환해라

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 <= 105
  • nums[i] is either 0 or 1.

Code

var findMaxConsecutiveOnes = function(nums) {
    let max = 0;
    let cnt = 0;
    
    for(let i=0; i < nums.length; i++) {
        if (nums[i] === 1)
            cnt ++;
        else {            
            cnt = 0;
        }
        max = Math.max(cnt, max);
    }
    
    return max;
};
Comments