2025-06-10 Daily Challenge
Today I have done leetcode's June LeetCoding Challenge with cpp
.
June LeetCoding Challenge 10
Description
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 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.
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 <= 100
s
consists only of lowercase English letters.s
contains at least one character with an odd frequency and one with an even frequency.
Solution
class Solution {
public:
int maxDifference(string s) {
int minEven = 100;
int maxOdd = 0;
vector<int> count(26);
for(auto c : s) {
c -= 'a';
count[c] += 1;
}
for(auto c : count) {
if(!c) continue;
if(c % 2 == 0) {
minEven = min(minEven, c);
} else {
maxOdd = max(maxOdd, c);
}
}
return maxOdd - minEven;
}
};
// Accepted
// 805/805 cases passed (3 ms)
// Your runtime beats 34.81 % of cpp submissions
// Your memory usage beats 94.49 % of cpp submissions (9.2 MB)