For example findConsecutiveMaxc c g g h a a a f f a b c c b

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 of the other characters. If multiple characters appear consecutively the maximum number of times, your function should return the character whose sequence comes first in the array. For example: findConsccutivcMax([c, a, a, a, b, c, c, c]) returns \'a\'. fmd(\'onsecutiveMax([s, h, a, k, c, w, e, i, g, h, t]) returns \'s\'. If the array is Empty or Null, return Null. b. Give the asymptotic (big Oh) complexity of the your algorithm in (a), show all the work you do.

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site