[Easy] 485. Max Consecutive Ones
Given a binary array nums, return the maximum number of consecutive 1’s in the array.
Examples
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^5nums[i]is either0or1.
Thinking Process
- Single Pass: Process each element exactly once
- Maintain a window
[left, right]satisfying a constraint. - Expand
rightto grow; shrinkleftwhen invalid. - Fixed window: slide both pointers together.
Common Approaches
Typical techniques for this pattern:
| Approach | Time | Space | Notes |
|---|---|---|---|
| Fixed-size window (this problem) | O(n) | O(1) | Window size known upfront |
| Variable-size window | O(n) | O(1) | Expand/shrink until valid |
| Window + hash map | O(n) | O(k) | Track character/count frequencies |
| Deque window max | O(n) | O(k) | Monotonic deque for max/min in window |
Solution
Time Complexity: O(n)
Space Complexity: O(1)
Use a simple counter to track consecutive ones. Reset the counter when encountering a zero, and update the maximum count whenever we see a one.
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxCnt = 0, cnt = 0;
for(int n : nums) {
if(n == 1) {
cnt++;
maxCnt = max(maxCnt, cnt);
} else {
cnt = 0;
}
}
return maxCnt;
}
};
Solution Explanation
Approach: Fixed-size window (this problem)
Key idea: 1. Single Pass: Process each element exactly once
How the code works:
- Single Pass: Process each element exactly once
- Maintain a window
[left, right]satisfying a constraint. - Expand
rightto grow; shrinkleftwhen invalid. - Fixed window: slide both pointers together.
- Maintain a window
Walkthrough — input nums = [1,1,0,1,1,1], expected output 3:
The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
| Aspect | Complexity | |——–|————| | Time | O(n) - Single pass through the array | | Space | O(1) - Only using two integer variables |
Algorithm Breakdown
1. Initialize Variables
int maxCnt = 0, cnt = 0;
maxCnt: Tracks the maximum consecutive ones seen so farcnt: Tracks the current consecutive ones streak
2. Iterate Through Array
for(int n : nums) {
Process each element in the array.
3. Handle Ones
if(n == 1) {
cnt++;
maxCnt = max(maxCnt, cnt);
}
- Increment current streak counter
- Update maximum if current streak is longer
4. Handle Zeros
else {
cnt = 0;
}
Reset the current streak counter to 0.
Complexity
| Aspect | Complexity | |——–|————| | Time | O(n) - Single pass through the array | | Space | O(1) - Only using two integer variables |
Why This Solution is Optimal
- Single Pass: Each element is visited exactly once - O(n) time
- Constant Space: Only uses two integer variables - O(1) space
- Simple Logic: Easy to understand and implement
- No Extra Data Structures: No need for arrays, maps, or sets
Common Mistakes
- All zeros:
[0,0,0]→0 - All ones:
[1,1,1]→3 - Single element (one):
[1]→1 - Single element (zero):
[0]→0 -
Alternating:
[1,0,1,0,1]→1 - Not resetting counter: Forgetting to reset
cntwhen encountering 0 - Not updating maxCnt during loop: Only updating maxCnt at the end
- Off-by-one errors: Incorrectly calculating the streak length
- Edge case handling: Not considering arrays with all zeros or all ones
Optimization Tips
Early Termination (if applicable)
If we know the array size and maximum possible, we could potentially terminate early, but for this problem, we need to check all elements.
Branchless Version
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxCnt = 0, cnt = 0;
for(int n : nums) {
cnt = (n == 1) ? cnt + 1 : 0;
maxCnt = max(maxCnt, cnt);
}
return maxCnt;
}
Related Problems
- 487. Max Consecutive Ones II - Can flip at most one 0
- 1004. Max Consecutive Ones III - Can flip at most k 0s
- 1446. Consecutive Characters - Similar problem with strings
- 1869. Longer Contiguous Segments of Ones than Zeros - Compare consecutive segments
Pattern Recognition
This problem demonstrates the “Consecutive Elements” pattern:
- Track current streak
- Reset streak when condition breaks
- Maintain maximum streak seen
This pattern appears in many problems:
- Longest increasing subsequence
- Longest palindrome substring
- Maximum subarray sum
Code Quality Notes
- Readability: The solution is clear and self-documenting
- Efficiency: Optimal time and space complexity
- Maintainability: Simple logic that’s easy to modify
- Robustness: Handles all edge cases correctly
This problem is a great introduction to the “consecutive elements” pattern, which is fundamental for many array and string problems.
Key Takeaways
- Single Pass: Process each element exactly once
- Counter Reset: Reset counter to 0 when encountering 0
- Track Maximum: Update maximum count whenever we see a 1
- Simple Logic: No complex data structures needed
References
- LC 485: Max Consecutive Ones on LeetCode
- LeetCode Discuss — LC 485: Max Consecutive Ones
- LeetCode Editorial (may require premium)