Max Consecutive Ones
LeetCode 485 | Difficulty: Easyβ
EasyProblem 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.
Basic problems that test fundamental programming skills.
Solutionsβ
Solution 1: C# (Best: 132 ms)β
| Metric | Value |
|---|---|
| Runtime | 132 ms |
| Memory | 32.9 MB |
| Date | 2019-03-17 |
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β
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
- 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.