Maximum Difference Between Even and Odd Frequency II Problem
Description
LeetCode Problem 3445.
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.
Example 1:
Input: s = "12233", k = 4
Output: -1
Explanation:
For the substring "12233", the frequency of '1' is 1 and the frequency of '3' is 2. The difference is 1 - 2 = -1.
Example 2:
Input: s = "1122211", k = 3
Output: 1
Explanation:
For the substring "11222", the frequency of '2' is 3 and the frequency of '1' is 2. The difference is 3 - 2 = 1.
Example 3:
Input: s = "110", k = 3
Output: -1
Constraints:
3 <= s.length <= 3 * 10^4sconsists only of digits'0'to'4'.- The input is generated that at least one substring has a character with an even frequency and a character with an odd frequency.
1 <= k <= s.length
Solution
Approach: Character Pairs, Sliding Window and Parity Prefixes
We look for a substring of length at least k where character a has an odd count and character b has an even count (at least two), maximizing count(a) - count(b). With only five digits, try all pairs (a, b) with a != b.
For a fixed pair, move the right end r over the string and keep the counts of a and b in the prefix [0, r] (curA, curB) and in the prefix before a left boundary (preA, preB). A substring is the difference of two prefixes, so its parities are decided by the parities of those prefix counts.
Keep best[i][j], the smallest preA - preB among valid left boundaries whose prefix counts have parities i and j. A left boundary is valid when the substring is at least k long and still has at least two b. As r grows, advance the left boundary while this holds and update best. Then, to make the substring's a odd and b even, combine with best[(curA & 1) ^ 1][curB & 1] and update the answer with curA - curB - best[...].
Complexity: O(n * 5^2) time and O(1) space.
from math import inf
class Solution:
def maxDifference(self, S: str, k: int) -> int:
s = list(map(int, S))
ans = -inf
for a in range(5):
for b in range(5):
if a == b:
continue
curA = curB = 0
preA = preB = 0
t = [[inf, inf], [inf, inf]]
l = -1
for r, x in enumerate(s):
curA += x == a
curB += x == b
while r - l >= k and curB - preB >= 2:
t[preA & 1][preB & 1] = min(t[preA & 1][preB & 1], preA - preB)
l += 1
preA += s[l] == a
preB += s[l] == b
ans = max(ans, curA - curB - t[curA & 1 ^ 1][curB & 1])
return ans