-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxDiff.js
More file actions
56 lines (44 loc) · 1.31 KB
/
maxDiff.js
File metadata and controls
56 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
You are given a string s consisting of lowercase English letters.
Your task is to find the maximum difference diff = freq(a1) - freq(a2) between the frequency of characters a1 and a2 in the string such that:
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:
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:
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:
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.
* @param {string} s
* @return {number}
*/
var maxDifference = function (s) {
let maxOdd = 0;
let minEven = 0;
let freqMap = new Map()
for (const char of s) {
freqMap.set(char, (freqMap.get(char) || 0) + 1);
}
let freqValues = [...freqMap.values()]
for (const freq of freqValues) {
if (freq % 2 === 1) {
maxOdd = Math.max(maxOdd, freq);
} else {
if (minEven === 0 || freq < minEven) {
minEven = freq;
}
}
}
return maxOdd - minEven;
};