LeetCode485-最大连续1的个数

题目链接

英文链接:https://leetcode.com/problems/max-consecutive-ones/

中文链接:https://leetcode-cn.com/problems/max-consecutive-ones/

题目详述

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

1
2
3
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

注意:

  • 输入的数组只包含 0 和1。
  • 输入数组的长度是正整数,且不超过 10,000。

题目详解

比较简单,直接统计并更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00485 {

public int findMaxConsecutiveOnes(int[] nums) {
int res = 0;
int cnt = 0;
for (int num : nums) {
if (num == 1) {
res = Math.max(res, ++cnt);
} else {
cnt = 0;
}
}
return res;
}
}