63 804
Assignments Done
99,5%
Successfully Done
In August 2018

Answer to Question #76527 in C++ for LEE JIA WEI

Question #76527
Write a function max_freq that takes in a string and returns maximum frequency of the characters in the string, i.e. the highest number of occurrences of a character.

Hint: You can use a std::map to maintain a count of the characters.

#include <string>

using namespace std;

int max_freq(string str) {
//code
}
Expert's answer
#include <string>
#include <map>

int max_freq(std::string str)
{
std::map<char, int> counts;
int maxCount = 0;
for (auto ch : str)
{
auto insertResult = counts.insert(std::pair<char, int>(ch, 1));
if (!insertResult.second)
insertResult.first->second++;

maxCount = std::max(maxCount, insertResult.first->second);
}
return maxCount;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions