No. of times a character occurs maximum number of times

what is the error in this code , please help

#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n;
int count;
cin>>n;
string str;
cin>>str;
for(int i=1;i<=n;i++)
{
if(str[i]==str[i+1])
{
count++;
}
}
cout<<count<<endl;
}

Run loop from 0 to n-1

2 Likes

Not working please help
Code link :
https://ide.geeksforgeeks.org/cEm5Okhv1D

initialize count to 0 then check.

1 Like

Printing 0 ???
Please check
https://ide.geeksforgeeks.org/G9r5M68WVo

Initialize count as 0 and run loop from 0 to n-2 since in your code i+1 is used…

1 Like

Not working
https://ide.geeksforgeeks.org/2w90AuiYiJ

#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int n;
int count=1,maxi=0;
cin>>n;
string str;
cin>>str;
sort(str.begin(),str.end());
for(int i=1;i<n;i++)
{
if(str[i]==str[i-1])
{
count++;
}
else
{
maxi=max(maxi,count);
count=1;
}
}
cout<<maxi<<endl;
}

Try this one

1 Like

Thanks it worked
But please check my code once

You weren’t actually counting the similar characters, you were counting just the adjacent one’s. So the answer was coming wrong. That’s why just sort the string so that all characters come together and then find the max among all.

1 Like

yea u r logic was wrong considering the question…I just corrected the large output issue that u were getting.

1 Like