Max Consecutive Ones

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

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

Analysis

可以用两个指针寻找连续1的边界,i为第一个连续1的第一个index,j为连续1的最后一个index + 1

110111
^ ^
i = 0, j = 2

110111_
   ^  ^
i = 3, j = 6

另外一种思路 from @yuxiangmusic on LeetCode

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

就是每次遇见了0就重新开始计数,不然增加当前记录的连续1的长度,比较所有的连续1长度就可以得到最大值。

比如:

Solution

Two Pointers - Two pointers for left and right boundaries each (8ms AC) - O(n) time, O(1) space

Keeping track of length of current consecutive ones - O(n) time, O(1) space

OR easier to read version @shawngao:

Reference

https://leetcode.com/problems/max-consecutive-ones/discuss/96693/Java-4-lines-concise-solution-with-explanation

Last updated

Was this helpful?