|
| 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 | + * - Pre-mark vowels in a boolean array of size 26 for O(1) lookup. |
| 12 | + * - Use two frequency arrays (size 26) to count vowels and consonants separately. |
| 13 | + * - Iterate over each character in the string: |
| 14 | + * - If it's a vowel, increment its count in the vowel frequency array. |
| 15 | + * - Otherwise, increment its count in the consonant frequency array. |
| 16 | + * - Scan both frequency arrays to find max frequency among vowels and consonants. |
| 17 | + * - Return their sum. |
| 18 | + * |
| 19 | + * Time Complexity: O(n + 26) ≈ O(n), where n = length of the string |
| 20 | + * Space Complexity: O(26) ≈ O(1), constant extra space |
| 21 | + */ |
| 22 | + |
| 23 | +class Solution { |
| 24 | + public int maxFreqSum(String s) { |
| 25 | + |
| 26 | + boolean[] vowels = new boolean[26]; |
| 27 | + for (char ch : new char[] { 'a', 'e', 'i', 'o', 'u' }) { |
| 28 | + vowels[ch - 'a'] = true; |
| 29 | + } |
| 30 | + |
| 31 | + int[] vowFreq = new int[26]; |
| 32 | + int[] conFreq = new int[26]; |
| 33 | + |
| 34 | + for (char ch : s.toCharArray()) { |
| 35 | + int index = ch - 'a'; |
| 36 | + if (vowels[index]) { |
| 37 | + vowFreq[index]++; |
| 38 | + } else { |
| 39 | + conFreq[index]++; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + int maxVow = 0; |
| 44 | + int maxCon = 0; |
| 45 | + for (int i = 0; i < 26; i++) { |
| 46 | + maxVow = Math.max(maxVow, vowFreq[i]); |
| 47 | + maxCon = Math.max(maxCon, conFreq[i]); |
| 48 | + } |
| 49 | + |
| 50 | + return maxVow + maxCon; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | + |
1 | 56 | /** |
2 | 57 | * Problem: Maximum Frequency Sum (custom problem) |
3 | 58 | * Difficulty: Easy |
|
0 commit comments