Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2472c3a

Browse files
authored
Create Maximum Difference Between Even and Odd Frequency II.py
1 parent 8580247 commit 2472c3a

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
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:
3+
4+
subs has a size of at least k.
5+
Character a has an odd frequency in subs.
6+
Character b has an even frequency in subs.
7+
Return the maximum difference.
8+
9+
Note that subs can contain more than 2 distinct characters.
10+
'''
11+
12+
13+
class Solution:
14+
def maxDifference(self, s: str, k: int) -> int:
15+
n = len(s)
16+
ans = float('-inf')
17+
18+
# Step 1: Try all (a, b) pairs
19+
for a in range(5):
20+
for b in range(5):
21+
if a == b: continue
22+
23+
s1 = [0] * (n + 1)
24+
s2 = [0] * (n + 1)
25+
26+
# Step 2: Prefix counts
27+
for i in range(1, n + 1):
28+
s1[i] = s1[i - 1] + (int(s[i - 1]) == a)
29+
s2[i] = s2[i - 1] + (int(s[i - 1]) == b)
30+
31+
# Step 3: Track best past difference for each parity
32+
g = [[float('-inf')] * 2 for _ in range(2)]
33+
j = 0
34+
35+
# Step 4: Two-pointer sliding window
36+
for i in range(k, n + 1):
37+
while i - j >= k and s1[i] > s1[j] and s2[i] > s2[j]:
38+
pa = s1[j] % 2
39+
pb = s2[j] % 2
40+
g[pa][pb] = max(g[pa][pb], s2[j] - s1[j])
41+
j += 1
42+
43+
# Step 5: Check candidate answer
44+
pa = s1[i] % 2
45+
pb = s2[i] % 2
46+
best = g[1 - pa][pb]
47+
if best != float('-inf'):
48+
ans = max(ans, (s1[i] - s2[i]) + best)
49+
50+
return -1 if ans == float('-inf') else ans

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /