Given a binary array nums
, return the maximum number of consecutive 1
's in the array.
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^5
nums[i]
is either0
or1
.
- Wednesday, 02 March, 2022
- Time Complexity:
$O(n)$ - Space Complexity:
$O(1)$ - Runtime: 36 ms, faster than 95.88% of C online submissions for Max Consecutive Ones.
- Memory Usage: 7.5 MB, less than 42.69% of C online submissions for Max Consecutive Ones.
int findMaxConsecutiveOnes(int *nums, int numsSize) {
int max_consec = 0;
int cur_consec = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == 1) {
cur_consec++;
max_consec = cur_consec > max_consec ? cur_consec : max_consec;
} else {
cur_consec = 0;
}
}
return max_consec;
}