485最大连续1的个数-数组
描述
给定一个二进制数组, 计算其中最大连续1的个数。
实例
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意
- 输入的数组只包含
0
和1
。 - 输入数组的长度是正整数,且不超过 10,000。
题解
遍历数组,如果值为1就counter++,否则将counter与max进行比较,去较大的一个.
static public int findMaxConsecutiveOnes(int[] nums) {
int counter = 0;
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1){
counter++;
} else {
max = Math.max(max,counter);
counter =0;
}
}
return max = Math.max(max,counter);
}