485. Max Consecutive Ones
485. Max Consecutive Ones
题目
Given a binary array nums
, return the maximum number of consecutive1
' 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
.
题目大意
给定一个二进制数组, 计算其中最大连续 1 的个数。
注意:
- 输入的数组只包含 0 和 1。
- 输入数组的长度是正整数,且不超过 10,000。
解题思路
- 给定一个二进制数组, 计算其中最大连续 1 的个数。
- 简单题。扫一遍数组,累计 1 的个数,动态维护最大的计数,最终输出即可。
代码
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let max = 0;
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
} else {
count = 0;
}
max = Math.max(max, count);
}
return max;
};
相关题目
相关题目
- [🔒 Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii)
- [1004. 最大连续 1 的个数 III](https://leetcode.com/problems/max-consecutive-ones-iii)
- [1446. 连续字符](https://leetcode.com/problems/consecutive-characters)
- [1869. 哪种连续子字符串更长](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros)
- [2414. 最长的字母序连续子字符串的长度](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring)
- [2511. 最多可以摧毁的敌人城堡数目](https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured)