Maximum Difference Between Even and Odd Frequency II - Problem
You are given a string s and an integer k. Your task is to find the maximum difference between the frequency of two characters, freq[a] - freq[b], in a substring subs of s, such that:
subshas a size of at leastk- Character
ahas an odd frequency insubs - Character
bhas a non-zero even frequency insubs
Return the maximum difference.
Note that subs can contain more than 2 distinct characters.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aabbc", k = 3
›
Output:
-1
💡 Note:
For all substrings of length >= 3: "aab" has a=2(even), b=1(odd), giving diff=1-2=-1. "abb" has a=1(odd), b=2(even), giving diff=1-2=-1. "bbc" has b=2(even), c=1(odd), giving diff=1-2=-1. "aabb" has all even frequencies, so invalid. "abbc" has a=1(odd), b=2(even), c=1(odd), giving max_odd=1, min_even=2, diff=-1. "aabbc" has a=2(even), b=2(even), c=1(odd), giving max_odd=1, min_even=2, diff=-1. The maximum difference is -1.
Example 2 — No Valid Combination
$
Input:
s = "aaa", k = 2
›
Output:
-1
💡 Note:
All possible substrings of length >= 2 are "aa", "aa", "aaa". In each case, 'a' has even frequency (2, 2, 3 respectively). Wait, 3 is odd! In "aaa": 'a' appears 3 times (odd). But we need both an odd-frequency character AND an even-frequency character. Since only 'a' exists and it has odd frequency, there's no even-frequency character, so return -1.
Example 3 — Multiple Characters
$
Input:
s = "abcabc", k = 4
›
Output:
-1
💡 Note:
For all substrings of length >= 4, we consistently get differences of -1 since the maximum odd frequency is 1 while minimum even frequency is 2. No substring gives a difference >= 0.
Constraints
- 1 ≤ s.length ≤ 105
- 1 ≤ k ≤ s.length
- s consists of only lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code