Post

3753 Maximum Difference Between Even And Odd Frequency I

3753 Maximum Difference Between Even And Odd Frequency I

Maximum Difference Between Even and Odd Frequency I image

You are given a string s consisting of lowercase English letters.

Your task is to find the maximum difference diff = a1 - a2 between the frequency of characters a1 and a2 in the string such that:

1
2
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:

1
2
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:

1
2
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:

1
2
3
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class Solution:
    def maxDifference(self, s: str) -> int:
        mp = {}

        for k in s:
            if k not in mp:
                mp[k] = 0
            mp[k] += 1
        even = 100000
        odd = 0
        for k, v in mp.items():
            if v % 2 == 0:
                even = min(even, v)
            else:
                odd = max(odd, v)
        return odd - even

        



This post is licensed under CC BY 4.0 by the author.