Skip to main content

Max Consecutive Ones

LeetCode 485 | Difficulty: Easy​

Easy

Problem Description​

Given a binary array nums, return the maximum number of consecutive 1's in the array.

Example 1:

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

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2

Constraints:

- `1 <= nums.length <= 10^5`

- `nums[i]` is either `0` or `1`.

Topics: Array


Approach​

Direct Approach​

This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.

When to use

Basic problems that test fundamental programming skills.


Solutions​

Solution 1: C# (Best: 132 ms)​

MetricValue
Runtime132 ms
Memory32.9 MB
Date2019-03-17
Solution
public class Solution {
public int FindMaxConsecutiveOnes(int[] nums) {
int result=0, start=0, end=0;
while (start<nums.Length)
{
if (nums[start] == 0) { start++; }
else
{
end = start;
while (end < nums.Length && nums[end] == 1)
end++;
result = Math.Max(result, end - start);
start = end;
}
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • LeetCode provides 1 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.

How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.