Max Consecutive Ones
Pattern: Traversal and in-place tricks
Find the longest run of 1s by counting the current run and resetting it on every 0.
The problem
You are given an array nums containing only 0s and 1s, with between 1 and 100,000 elements. Return the length of the
longest unbroken run of 1s. For example, the answer for [1, 1, 0, 1, 1, 1] is 3.
The function name findMaxConsecutiveOnes matches LeetCode. Use the link above for the exact statement.
Think first
- What two numbers do you need while walking: one about now, one about the past?
- What happens to the current run when you meet a 0?
- If the longest run is at the very end, will your answer still be updated?
Hints
Brute force, and why it fails
From every starting index, count how many 1s follow without a break, and keep the largest count. That is O(n²) in the worst case (all 1s). One pass with a running count is O(n).
The key insight
A run's length only depends on whether the current element extends it or breaks it. So one counter for "now" and one for "best" are enough.
Dry run
| run | 0 |
|---|---|
| best | 0 |
nums = [1, 1, 0, 1, 1, 1]. run is the length of the current run of 1s, and best is the longest seen.
The plan
best = 0
run = 0
for x in nums:
if x == 1:
run = run + 1
best = max(best, run)
else:
run = 0 # a 0 ends the run
return best
Complexity
- Time
O(n)- Space
O(1)
One pass, two counters.
Edge cases
- All 0s: 0.
- All 1s: the length of the array.
- The longest run at the end:
bestis updated inside the loop, so it is counted.
I've built my logic, show the code
Java
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int best = 0;
int run = 0; // length of the current run of 1s
for (int x : nums) {
if (x == 1) {
run++;
best = Math.max(best, run);
} else {
run = 0; // a 0 ends the run
}
}
return best;
}
}C++
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int best = 0;
int run = 0; // length of the current run of 1s
for (int x : nums) {
if (x == 1) {
run++;
best = max(best, run);
} else {
run = 0; // a 0 ends the run
}
}
return best;
}
};Python
class Solution:
def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
best = 0
run = 0 # length of the current run of 1s
for x in nums:
if x == 1:
run += 1
best = max(best, run)
else:
run = 0 # a 0 ends the run
return bestCommon mistakes
- Updating
bestonly when a 0 appears, which misses a run that reaches the end. - Forgetting to reset
runon a 0. - Starting
runat 1.