Skip to content
thesarfo

Reference

Maximum Consecutive Ones

Tracking the longest run of consecutive 1s in a binary array in a single pass, including the trailing-run edge case.

views 0

Longest run of consecutive 1s in a binary array. [1,1,0,1,1,1,0,1,1]3. (LeetCode 485)

class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int maxCount = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 1) {
count++;
} else {
maxCount = std::max(maxCount, count);
count = 0;
}
}
// Final comparison in case the array ends with a run of 1s
maxCount = std::max(maxCount, count);
return maxCount;
}
};

Time: O(n). Space: O(1). The final comparison after the loop matters — without it, a trailing run of 1s (with no 0 after it) would never get counted.