Input: s ="aaaaabbc"Output: 3Explanation:
* The character `'a'` has an **odd frequency** of `5`, and `'b'` has an **even frequency** of `2`.* The maximum difference is`5 - 2 = 3`.
Input: s ="abcabcab"Output: 1Explanation:
* The character `'a'` has an **odd frequency** of `3`, and `'c'` has an **even frequency** of 2.* The maximum difference is`3 - 2 = 1`.
The key idea is to count the frequency of each character in the string, then find the highest frequency among characters with odd counts (a1) and the lowest frequency among characters with even counts (a2). The answer is the maximum difference a1 - a2. This works because the problem asks for the largest possible difference between an odd and an even frequency.
classSolution {
publicintmaxDifference(String s) {
int[] freq =newint[26];
for (char c : s.toCharArray()) freq[c -'a']++;
int maxOdd = 0, minEven = 101;
for (int f : freq) {
if (f == 0) continue;
if (f % 2 == 1 && f > maxOdd) maxOdd = f;
if (f % 2 == 0 && f < minEven) minEven = f;
}
return maxOdd - minEven;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funmaxDifference(s: String): Int {
val freq = IntArray(26)
for (c in s) freq[c - 'a']++var maxOdd = 0var minEven = 101for (f in freq) {
if (f ==0) continueif (f % 2==1&& f > maxOdd) maxOdd = f
if (f % 2==0&& f < minEven) minEven = f
}
return maxOdd - minEven
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defmaxDifference(self, s: str) -> int:
freq: list[int] = [0] *26for c in s:
freq[ord(c) - ord('a')] +=1 max_odd: int =0 min_even: int =101for f in freq:
if f ==0:
continueif f %2==1and f > max_odd:
max_odd = f
if f %2==0and f < min_even:
min_even = f
return max_odd - min_even
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmax_difference(s: String) -> i32 {
letmut freq = [0; 26];
for b in s.bytes() {
freq[(b -b'a') asusize] +=1;
}
letmut max_odd =0;
letmut min_even =101;
for&f in&freq {
if f ==0 { continue; }
if f %2==1&& f > max_odd { max_odd = f; }
if f %2==0&& f < min_even { min_even = f; }
}
max_odd - min_even
}
}