“Find Maximum Consecutive 1s in a Binary Array in C”
C
Medium
3 views
Problem Description
It's a binary array (0 and 1), you need to find the length of the maximum consecutive 1s - when will the counter reset logic be applied?
Official Solution
#include <stdio.h>
int main() {
int arr[] = {1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1};
int size = sizeof(arr) / sizeof(arr[0]);
int currentCount = 0;
int maxCount = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == 1) {
currentCount++; // count consecutive 1s
if (currentCount > maxCount)
maxCount = currentCount;
} else {
currentCount = 0; // reset counter when 0 occurs
}
}
printf("Maximum consecutive 1s: %dn", maxCount);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!