#3442
Easy Algorithms Maximum difference between even and odd frequency i
Hash Table String Counting
60.7% acceptance
Feb 25, 2026
394
71
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:
a1 has an odd frequency in the string.
a2 has an even frequency in the string.
Return this maximum difference.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_difference(s: String) -> i32 {
let mut freq = [0i32; 26];
for b in s.bytes() { freq[(b - b'a') as usize] += 1; }
let max_odd = freq.iter().filter(|&&f| f > 0 && f % 2 == 1).cloned().max().unwrap_or(0);
let min_even = freq.iter().filter(|&&f| f > 0 && f % 2 == 0).cloned().min().unwrap_or(0);
max_odd - min_even
}
}