Algorithm Analysis
Declare a data structure map<string, int> m
, in which we will count how many times each word occurred. Then find the word that occurred the most times. If there are several such words, then we output the lexicographically largest one.
Algorithm Implementation
In the map m
, we count how many times each word occurred.
map<string,int> m;
Read and count words.
cin >> n; for (i = 0; i < n; i++) { cin >> s; m[s]++; }
Find the word res
, which occurs the most number of times mx
.
mx = 0; for (auto x : m) { if (x.second >= mx) { mx = x.second; res = x.first; } }
Output the word with the maximum frequency and the frequency itself.
cout << res << " " << mx << endl;
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); TreeMap<String, Integer> tree = new TreeMap<String, Integer>(); int test = con.nextInt(); while(test-- > 0) { String s = con.next(); tree.put(s, tree.getOrDefault(s, 0) + 1); } int max = -1; String res = null; for(String s : tree.keySet()) { int n = tree.get(s); if (n >= max) { res = s; max = n; } } System.out.println(res + " " + max); con.close(); } }