Count of maximum-CHFMAX

c-plus-plus
codechef
wrong-answer

#1

What is wrong in this code

int main()
{

string str;

int arr[256]={0};

int t;

cin>>t;

for(int i=0;i<t;i++)

{
    cin>>str;
    
    for(int j=0;j<str.length();j++)
    {
    
        arr[str[j]]++;
    }
    int maxm=-1,pos=0;
                     char val;
                for(int m=0;m<256;m++)
                     {
                         if(arr[m]>=maxm&&arr[m]>0)
                         {
                             if(arr[m]==maxm)
                             {
                                 if(m>pos)
                                    maxm=arr[pos];

                             }
                             else
                             {
                                 maxm=arr[m];
                                 pos=m;
                             }
                         }



                }
           for(int j=0;j<256;j++)
            {


                if(arr[j]==maxm)
                {val=j;
                break;
            }}

    for(int i=0;i<str.length();i++)
    {

        if(str*==val)
            str*='?';
    }
    cout<<str<<endl;
    }
    return 0;
}

#2

I think problem in you code is that you are not intialising array arr to 0 after every test case due to which previous frequencies of characters of old string are also getting added.


#3

Declare int arr[256] = {0} inside for loop that is counting test case.
i.e

for(int i = 0; i < t;i++)
{
   int arr[256] = {0};
   //rest of the code..
}

This is because, if you do not initialise array values to zero for every test case, they take the values that remained in the array after previous test case. So count of frequency of characters differ.

Ex : let this be input

2
aba
abcd

With your code, frequencies of characters in second test case would give a = 3, b = 2, c = 1, d = 1.