Find largest alternating 1s and 0s subsequence in a string containing only 1s and 0s.also find the starting index for the largest subsequence
Example for 1101011 rhe longest alternating subsequence length is 5 from index 1 to 5.
Tried doing it by comparing consecutive elements and if they are not equal checking current length with max size. Need help with code
int findSubArray(int arr[], int n)
{
int sum = 0;
int maxsize = -1, startindex = 0;
int endindex = 0;
int j = 0;
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i+1] && maxsize < i - j + 1)
{
maxsize = i - j + 1;
startindex = j;
} else {
j = i;
}
}
endindex = startindex+maxsize-1;
if (maxsize == -1)
System.out.println("No such subarray");
else
System.out.println(startindex+" to "+endindex);
return maxsize;
}
Aucun commentaire:
Enregistrer un commentaire