Created
June 10, 2025 20:15
-
-
Save tatsuyax25/5f4aa87f62d4d72b7ff5eb391bae09b0 to your computer and use it in GitHub Desktop.
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.
a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
var maxDifference = function(s) { | |
// Step 1: Count frequencies of each character | |
const freqMap = {}; // Object to store frequency of each character | |
for (const char of s) { | |
freqMap[char] = (freqMap[char] || 0) + 1; // Increment frequency count | |
} | |
// Step 2: Separate characters with odd and even frequencies | |
let maxOdd = -Infinity; // Track the highest odd frequency | |
let minEven = Infinity; // Track the lowest even frequency | |
for (const [char, freq] of Object.entries(freqMap)) { | |
if (freq % 2 === 1) { // Odd frequency | |
maxOdd = Math.max(maxOdd, freq); | |
} else { | |
minEven = Math.min(minEven, freq); | |
} | |
} | |
// Step 3: Compute the maximum difference | |
return maxOdd === -Infinity || minEven === Infinity ? 0 : maxOdd - minEven; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment