485. Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones/

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

1
2
3
4
5
Example 1:
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:

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

java


https://discuss.leetcode.com/topic/75437/java-4-lines-concise-solution-with-explanation

Java 4 lines concise solution with explanation

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

The idea is to reset maxHere to 0 if we see 0, otherwise increase maxHere by 1
The max of all maxHere is the solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
110111
^ maxHere = 1

110111
.^ maxHere = 2

110111
..^ maxHere = 0

110111
...^ maxHere = 1

110111
....^ maxHere = 2

110111
.....^ maxHere = 3

We can also solve this problem by setting k = 0 of Max Consecutive Ones II


https://discuss.leetcode.com/topic/75430/easy-java-solution

Easy Java Solution

This is a really easy problem. No explanation :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int result = 0;
int count = 0;

for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
result = Math.max(count, result);
}
else count = 0;
}

return result;
}
}

https://discuss.leetcode.com/topic/75470/concise-java-solution-without-if

Concise Java Solution without “if”.

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxSum = 0, sum = 0;
for (int n : nums) {
sum *= n;
sum += n;
maxSum = Math.max(maxSum, sum);
}
return maxSum;
}
}

python


https://discuss.leetcode.com/topic/75425/simple-python

Simple Python

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
cnt = 0
ans = 0
for num in nums:
if num == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans

谢谢你,可爱的朋友。