|
| 1 | +/** |
| 2 | + * Problem: Maximum Frequency Sum (custom problem) |
| 3 | + * Difficulty: Easy |
| 4 | + * |
| 5 | + * Description: |
| 6 | + * - Given a string, count the frequencies of vowels and consonants. |
| 7 | + * - Find the maximum frequency among vowels and the maximum frequency among consonants. |
| 8 | + * - Return the sum of these two maximum frequencies. |
| 9 | + * |
| 10 | + * Approach: |
| 11 | + * - Use two HashMaps: one for vowels, one for consonants. |
| 12 | + * - Iterate over each character in the string. |
| 13 | + * - If it's a vowel, update the vowel map. |
| 14 | + * - Otherwise, update the consonant map. |
| 15 | + * - Find the maximum frequency from vowels and from consonants. |
| 16 | + * - Return their sum. |
| 17 | + * |
| 18 | + * Time Complexity: O(n) where n = length of string |
| 19 | + * Space Complexity: O(k) where k = number of distinct characters (at most 26 for lowercase English letters) |
| 20 | + */ |
| 21 | + |
| 22 | +class Solution { |
| 23 | + HashMap<Character, Integer> vMap = new HashMap<>(); |
| 24 | + HashMap<Character, Integer> cMap = new HashMap<>(); |
| 25 | + |
| 26 | + public int maxFreqSum(String s) { |
| 27 | + for (char ch : s.toCharArray()) { |
| 28 | + if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { |
| 29 | + vMap.put(ch, vMap.getOrDefault(ch, 0) + 1); |
| 30 | + } else { |
| 31 | + cMap.put(ch, cMap.getOrDefault(ch, 0) + 1); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + int maxV = 0; |
| 36 | + // find max vowel frequency |
| 37 | + for (int val : vMap.values()) { |
| 38 | + if (val > maxV) { |
| 39 | + maxV = val; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + int maxC = 0; |
| 44 | + // find max consonant frequency |
| 45 | + for (int val : cMap.values()) { |
| 46 | + if (val > maxC) { |
| 47 | + maxC = val; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return maxV + maxC; |
| 52 | + } |
| 53 | +} |
0 commit comments