#485

Max Consecutive Ones

Easy
ArraySliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the array to count consecutive 1's. This is efficient and avoids unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two variables: max_count to track the maximum consecutive 1's and current_count to count the current streak of 1's.
  2. 2Step 2: Iterate through each element in the array.
  3. 3Step 3: If the current element is 1, increment current_count. If it's 0, reset current_count to 0.
  4. 4Step 4: After each increment, update max_count if current_count exceeds it.
solution.py12 lines
1# Full working Python code
2
3def findMaxConsecutiveOnes(nums):
4    max_count = 0
5    current_count = 0
6    for num in nums:
7        if num == 1:
8            current_count += 1
9            max_count = max(max_count, current_count)
10        else:
11            current_count = 0
12    return max_count

Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) as we only use a few variables for counting.

  • 1The problem can be solved by counting streaks of 1's.
  • 2Using a single pass is more efficient than nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.