For example findConsecutiveMaxc c g g h a a a f f a b c c b
Solution
// C++ program to find the maximum consecutive repeating character
#include <iostream>
using namespace std;
char findConsecutiveMax(char array[], int n)
{
char maxChar = array[0];
int count = 1;
int maxCount = 1;
for (int i = 2; i < n; i++)
{
if (array[i] != array[i-1])
{
if (count > maxCount)
{
maxChar = array[i-1];
maxCount = count;
}
count = 1;
}
else
{
count++;
}
}
return maxChar;
}
int main()
{
char array1[] = {\'c\',\'c\',\'g\',\'g\',\'h\',\'a\',\'a\',\'a\',\'f\',\'f\',\'a\',\'b\',\'c\',\'c\',\'b\',\'c\'};
char array2[] = {\'c\',\'a\',\'a\',\'a\',\'b\',\'a\',\'a\',\'a\'};
char array3[] = {\'s\',\'h\',\'a\',\'k\',\'e\',\'w\',\'e\',\'i\',\'g\',\'h\',\'t\'};
int n1 = sizeof(array1)/sizeof(array1[0]);
int n2 = sizeof(array2)/sizeof(array2[0]);
int n3 = sizeof(array3)/sizeof(array3[0]);
cout << \"Maximum consecutive repeating character: \" << findConsecutiveMax(array1, n1) << endl;
cout << \"Maximum consecutive repeating character: \" << findConsecutiveMax(array2, n2) << endl;
cout << \"Maximum consecutive repeating character: \" << findConsecutiveMax(array3, n3) << endl;
return 0;
}
/*
In function findConsecutiveMax, the character array is iterated only once
to find the maximum consecutive repeating character
Thus, Time complexity: O(n)
output:
Maximum consecutive repeating character: a
Maximum consecutive repeating character: a
Maximum consecutive repeating character: s
*/
![For example. findConsecutiveMax([c, c, g, g, h, a, a, a, f, f, a, b, c, c, b, c]) should return \'a\', because it appears three times in a row- more than any o For example. findConsecutiveMax([c, c, g, g, h, a, a, a, f, f, a, b, c, c, b, c]) should return \'a\', because it appears three times in a row- more than any o](/WebImages/18/for-example-findconsecutivemaxc-c-g-g-h-a-a-a-f-f-a-b-c-c-b-1036355-1761537782-0.webp)
![For example. findConsecutiveMax([c, c, g, g, h, a, a, a, f, f, a, b, c, c, b, c]) should return \'a\', because it appears three times in a row- more than any o For example. findConsecutiveMax([c, c, g, g, h, a, a, a, f, f, a, b, c, c, b, c]) should return \'a\', because it appears three times in a row- more than any o](/WebImages/18/for-example-findconsecutivemaxc-c-g-g-h-a-a-a-f-f-a-b-c-c-b-1036355-1761537782-1.webp)