Sponsored
Sponsored
This approach involves iterating through the array and counting sequences of 1s. If a 0 is encountered, the count is reset to 0. We keep track of the maximum count during the iteration.
Time Complexity: O(n), where n is the number of elements in the array, as we make a single pass.
Space Complexity: O(1) since no extra space proportional to input size is used.
1#include <stdio.h>
2
3int findMaxConsecutiveOnes(int* nums, int numsSize) {
4 int maxCount = 0, currentCount = 0;
5 for(int i = 0; i < numsSize; i++) {
6 if(nums[i] == 1) {
7 currentCount++;
8 if(currentCount > maxCount) {
9 maxCount = currentCount;
10 }
11 } else {
12 currentCount = 0;
13 }
14 }
15 return maxCount;
16}
17
18int main() {
19 int nums[] = {1, 1, 0, 1, 1, 1};
20 int size = sizeof(nums) / sizeof(nums[0]);
21 int result = findMaxConsecutiveOnes(nums, size);
22 printf("The maximum number of consecutive 1s is: %d\n", result);
23 return 0;
24}
The function findMaxConsecutiveOnes
iterates over the input array nums
. It uses a counter to track consecutive ones. When a one is encountered, the counter is incremented. If a zero is encountered, the counter is reset. Throughout the iteration, the maximum sequence length is updated.
In this version, two pointers left
and right
maintain the window of consecutive 1s. When a 0 is found, left
is moved to right + 1
, effectively 'skipping' the segments with 0s, adjusting the window accordingly.