# Sequence with largest size of subsequence having each element as same

2524 views
4

I want to find out the largest continuous subsequence having every element equal to 5 .

I tried writing a code for this but couldn't figure out the right method

example -> if sequence is like 5 5 1 0 93 43 5 5 5 5 21 answer will be 4 since 4 continuous 5's are present in the array . P.S. - I'm a newbie stuck on it .

``````int large(int a[],int n){

int i=0,j=0,sublen=0;
while(i<n){

if(a[i]==1)
{
sublen++;
for(int j=i+1;j<n;j++){
if(a[j]==1){
sublen++;
}
else{
i=j+1;
continue;
}
}
}
else{
i++;
}
}
return sublen;
}
``````

4

You could simply iterate through the sequence, when you see a 5 then increment a counter otherwise reset the counter to 0. When you increment the counter test to see if it's the largest value it's held so far. At the end return the largest value.

Something like:

``````int large(const int *a, int n)
{
int sublen = 0, counter = 0;

for (int i = 0; i < n; ++i) {
if (a[i] == 5) { // found a 5
++counter;
if (sublen < counter) { // test for largest value so far
sublen = counter;
}
} else { // not a 5
counter = 0;
}
}
return sublen;
}
``````

posted this