3442. Maximum Difference Between Even and Odd Frequency I
SourceWeekly Contest 435 Q1DifficultyEasyRating1220
Description
You are given a string s consisting of lowercase English letters.
Your task is to find the maximum difference diff = freq(a1) - freq(a2) between the frequency of characters a1 and a2 in the string such that:
a1has an odd frequency in the string.a2has an even frequency in the string.
Return this maximum difference.
Example 1:
Input: s = "aaaaabbc"
Output: 3
Explanation:
- The character
'a'has an odd frequency of5, and'b'has an even frequency of2. - The maximum difference is
5 - 2 = 3.
Example 2:
Input: s = "abcabcab"
Output: 1
Explanation:
- The character
'a'has an odd frequency of3, and'c'has an even frequency of 2. - The maximum difference is
3 - 2 = 1.
Constraints:
3 <= s.length <= 100sconsists only of lowercase English letters.scontains at least one character with an odd frequency and one with an even frequency.
Solutions
Solution 1: Counting
Thinking
We need the largest odd frequency minus the smallest even frequency. A single count over lowercase letters suffices.
The statement is about the whole string, not a substring.
Scan a counter, take the max odd and the min even, and return their difference.
We can use a hash table or an array \(\textit{cnt}\) to record the occurrences of each character in the string \(s\). Then, we traverse \(\textit{cnt}\) to find the maximum frequency \(a\) of characters that appear an odd number of times and the minimum frequency \(b\) of characters that appear an even number of times. Finally, we return \(a - b\).
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(|\Sigma|)\), where \(\Sigma\) is the character set. In this problem, \(|\Sigma| = 26\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |