Maximum Difference Between Even and Odd Frequency I Problem
#3442
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3442.
You are given a string s consisting of lowercase English letters.
Your task is to find the maximum difference diff = freq(a_1) - freq(a_2) between the frequency of characters a_1 and a_2 in the string such that:
a_1has an odd frequency in the string.a_2has 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 of 5, and 'b' has an even frequency of 2.
- The maximum difference is 5 - 2 = 3.
Example 2:
Input: s = "abcabcab"
Output: 1
Explanation:
- The character 'a' has an odd frequency of 3, 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.
Solution
Approach: Counting
Count each character. The best difference takes the largest odd frequency a and the smallest even frequency b, so the answer is a - b.
Complexity: O(n) time and O(1) space (26 counters).
from collections import Counter
from math import inf
class Solution:
def maxDifference(self, s: str) -> int:
cnt = Counter(s)
a, b = 0, inf
for v in cnt.values():
if v % 2:
a = max(a, v)
else:
b = min(b, v)
return a - b