DSA
Maximum Consecutive Ones
Optimal approach. Optimal — Time O(n), Space O(1).
Given a binary array nums, return the maximum number of consecutive 1s in the array.
A binary array is an array that contains only 0s and 1s.
Optimal Solution#
Walk through the binary array with a single pass, maintaining a counter curr that increments on each 1 and resets to zero on each 0. Whenever we reset, we compare curr against the global maximum before clearing it. A final comparison after the loop handles the case where the array ends with a run of ones. This requires only two variables and runs in O(n) time with O(1) space — optimal since we must read every element at least once.
cpp
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxi = 0;
int curr =0;
for(int i=0;i<nums.size();i++){
if(nums[i] != 1){
maxi = max(maxi, curr);
curr=0;
}else{
curr++;
}
}
if(curr)
maxi = max(maxi, curr);
return maxi;
}
};
Time Complexity: O(n)
Space Complexity: O(1)