← All problems · Arrays & Searching
Longest Alternating Even-Odd Subarray
Return the length of the longest contiguous subarray whose adjacent elements alternate between even and odd. Return zero for an empty array.
Implement size_t longest_alternating(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.
Compare the parity of adjacent values.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
size_t longest_alternating(const int *a, size_t n)
{
if(!n)return 0;
size_t run=1,best=1;
for(size_t i=1;i<n;++i){
run=(((unsigned)a[i] ^ (unsigned)a[i-1]) & 1u) ? run+1 : 1;
if(run>best)best=run;
}
return best;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::size_t longest_alternating(const int *a, std::size_t n)
{
if(!n)return 0;
std::size_t run=1,best=1;
for(std::size_t i=1;i<n;++i){
run=(((unsigned)a[i] ^ (unsigned)a[i-1]) & 1u) ? run+1 : 1;
if(run>best)best=run;
}
return best;
}
Extend the current run when parity changes; otherwise reset it to one.
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[]={10,12,8,4}, b[]={2,4,3,2,1,8}, c[]={-1,-2,-3};
CHECK(longest_alternating(a,4)==1);
CHECK(longest_alternating(b,6)==5);
CHECK(longest_alternating(c,3)==3);
CHECK(longest_alternating(NULL,0)==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}