Skip to content

Commit afd60b3

Browse files
committed
Add solution
1 parent 8f2f1db commit afd60b3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// 3445. Maximum Difference Between Even and Odd Frequency II
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+
// subs has a size of at least k.
4+
// Character a has an odd frequency in subs.
5+
// Character b has a non-zero even frequency in subs.
6+
// Return the maximum difference.
7+
// Note that subs can contain more than 2 distinct characters.
8+
9+
10+
// Solution: Prefix Sum & Sliding Window
11+
12+
// Enumerate each pair of (i, j), where i is the character with odd frequency and j is the even one.
13+
14+
// Maintain a sliding window of at least size k, and contains at least 2 occurances of j.
15+
// Keep track of:
16+
// Prefix sum of the current difference (count i - count j).
17+
// Parity of occurances of i and j.
18+
// Store the minimum score for each key (parity of count of i, parity of count of j), for indices that we are moving out of the window.
19+
// To find the maximum difference, find the maximum (current score - minimum score with a key of parity (flipped, same)).
20+
21+
// Time Complexity: O(25n) 209ms
22+
// Space Complexity: O(1) 62MB
23+
function maxDifference(s, k) {
24+
const n = s.length;
25+
let maxDiff = -Infinity;
26+
for (let i = 0; i <= 4; i++) {
27+
for (let j = 0; j <= 4; j++) {
28+
if (i === j) continue;
29+
const minScore = Array(2).fill(0).map(() => Array(2).fill(Infinity));
30+
minScore[0][0] = 0;
31+
let oddCount = 0, evenCount = 0;
32+
let prevOddCount = 0, prevEvenCount = 0;
33+
let l = 0;
34+
for (let r = 0; r < n; r++) {
35+
oddCount += s[r] == i ? 1 : 0;
36+
evenCount += s[r] == j ? 1 : 0;
37+
// we only store minimum score for previous indices if the window has at least two occurrances of j
38+
while (r - l >= k && evenCount - prevEvenCount >= 2) {
39+
prevOddCount += s[l] == i ? 1 : 0;
40+
prevEvenCount += s[l] == j ? 1 : 0;
41+
minScore[prevOddCount % 2][prevEvenCount % 2] = Math.min(prevOddCount - prevEvenCount, minScore[prevOddCount % 2][prevEvenCount % 2]);
42+
l++;
43+
}
44+
if (r >= k - 1 && oddCount > 0 && evenCount > 0) {
45+
const currScore = oddCount - evenCount;
46+
maxDiff = Math.max(maxDiff, currScore - minScore[1 ^ (oddCount % 2)][evenCount % 2]);
47+
}
48+
}
49+
}
50+
}
51+
return maxDiff;
52+
};
53+
54+
// Three test cases
55+
console.log(maxDifference("12233", 4)) // -1
56+
console.log(maxDifference("1122211", 3)) // 1
57+
console.log(maxDifference("110", 3)) // -1

0 commit comments

Comments
 (0)