</>EmbeddedInterview
← All problems · Arrays & Searching

Maximum Consecutive Ones in a Binary Array

Easy

Given an array containing only 0 and 1, return the length of its longest contiguous run of ones. Implement size_t max_ones(const int *a, size_t n).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Reset the running count at every zero.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>

size_t max_ones(const int *a, size_t n)
{
    size_t run=0,best=0;
    for(size_t i=0;i<n;++i){run=a[i]==1 ? run+1 : 0;if(run>best)best=run;}
    return best;
}

Keep the largest run observed so far. Time O(n), extra space O(1).

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int a[]={1,1,0,1,1,1,0}, b[]={0,0,0}, c[]={1,1};
    CHECK(max_ones(a,7)==3);
    CHECK(max_ones(b,3)==0);
    CHECK(max_ones(c,2)==2);
    CHECK(max_ones(NULL,0)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}