1. 题目描述
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
2. Java代码
public int findMaxConsecutiveOnes(int[] nums) {
// base case,数组为空时返回0
if (nums.length == 0) return 0;
// 计数
int count = 0;
// 连续个数最多的个数
int result = 0;
// 遍历数组
for (int i = 0; i < nums.length; i++) {
// 遇到1则连续的个数加一
if (nums[i] == 1) count++;
// 遇到0,则先保留前面已经计算过的连续个数的最大值并使计数归零进行下一轮的计算
else {
// 保存已经计算过的连续个数的最大值
result = Math.max(count,result);
count = 0;
}
}
// 返回最大值
return Math.max(count,result);
}