[LeetCode] Maximum Difference Between Even and Odd Frequency I

3442. Maximum Difference Between Even and Odd Frequency I

You are given a string s consisting of lowercase English letters. Your task is to find the maximum difference between the frequency of two characters in the string such that:

  • One of the characters has an even frequency in the string.
  • The other character has an odd frequency in the string.

Return the maximum difference, calculated as the frequency of the character with an odd frequency minus the frequency of the character with an even frequency.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maxDifference(string s) {
vector<int> freq(26);
for(auto& ch : s) freq[ch-'a']++;
int res = INT_MIN;
for(int i = 0; i < 26; i++) {
if(!freq[i]) continue;
if(freq[i] & 1) continue;
for(int j = 0; j < 26; j++) {
if(!freq[j]) continue;
if(freq[j] % 2 == 0) continue;
int now = freq[i] - freq[j];
res = max(res, -now);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/02/PS/LeetCode/maximum-difference-between-even-and-odd-frequency-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.