Max Consecutive Ones
LeetCode 485 · Easy · solution, intuition & step-by-step walkthrough
Running streak, reset on non-1.
This is how I solved Max Consecutive Ones (LeetCode 485), an easy problem from the Linear Scan pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Keep a running count of the current streak of 1s; reset it to 0 at any other value, and remember the longest streak seen.
Approach
- 1
count = 0, maxLength = 0.
- 2
1 → count++; otherwise count = 0.
- 3
Update maxLength each step.
How I solved it
Running countPythonO(n) time · O(1) space
class Solution:
def findMaxConsecutiveOnes(self, nums):
maxLength = 0
count = 0
for i in range(len(nums)):
if nums[i] != 1:
count = 0
else:
count += 1
maxLength = max(maxLength, count)
return maxLengthMax Consecutive Ones — FAQ
What is the intuition behind Max Consecutive Ones?
Keep a running count of the current streak of 1s; reset it to 0 at any other value, and remember the longest streak seen.
How do you solve Max Consecutive Ones (LeetCode 485)?
1. count = 0, maxLength = 0. 2. 1 → count++; otherwise count = 0. 3. Update maxLength each step.
What is the time and space complexity of Max Consecutive Ones?
Time: O(n). Space: O(1). (Accepted approach: Running count.)
What are common mistakes in Max Consecutive Ones?
Update the maximum on every step, not only on resets.