485.最重要的连续1的数量(javascript)485.MaxConsecutiveOnes

原创
小哥 3年前 (2022-11-10) 阅读数 3 #大杂烩

给定一个二进制数组 nums , 计算最大连续 1 的个数。
Given a binary array nums, return the maximum number of consecutive 1’s in the array.

示例 1:

输入:nums = [1,1,0,1,1,1]
输出:3
说明:前两个和后三个是连续的。 1 ,所以最大连续 1 的个数是 3.

示例 2:

输入:nums = [1,0,1,1,0,1]
输出:2

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

提示:

1 <= nums.length <= 105
nums[i] 不是 0 就是 1.

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function (nums) {
    let n = 0
    let max = 0
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            n++
        } else {
            //当遇到0,需要重置连续中断0
            n = 0
        }
        //取每个循环的最大值。
        max = Math.max(max, n)
    }
    return max
};

leetcode: https://leetcode.cn/problems/max-consecutive-ones/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除