【leetcode】485. max consecutive ones

Description

Given a binary array, find the maximum number of consecutive 1s in this array.

Example

Input: [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.

Note

1.The input array will only contain 0 and 1.
2.The length of input array is a positive integer and will not exceed 10,000

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int (int[] nums) {
int len = nums.length;
int max = 0;
int count = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == 1) {
count++;
max = Math.max(max, count);
} else {
count = 0;
}
}
return max;
}

Result

AC

Analyse

遍历的问题。

Optimization

1
2
3
4
5
6
7
8
public int (int[] nums) {
int max = 0;
int maxHere = 0;
for (int i : nums) {
max = Math.max(max, maxHere = (i == 0 ? 0 : maxHere + 1));
}
return max;
}

Analyse

不影响可读性的情况下,更短的代码果然显得更美。