This question is like quite straightforward I reckon.
Just iterate through the string s, keeping track of each letter's frequency as you iterate through it using a hashmap.
Afterwards, just iterate through all the letters and find the:
maxOddthe maximum odd count of a letterminEventhe minimum even count of a letter
Then, simply return maxOdd - minEven as the solution.
code
class Solution {
public:
int maxDifference(string s) {
int alphabetFrequency[26] = {0};
for (char c : s) {
++alphabetFrequency[c-'a'];
}
int minEven = INT32_MAX;
int maxOdd = 0;
for (int i = 0; i < 26; ++i) {
if (alphabetFrequency[i] != 0) {
if (alphabetFrequency[i] % 2 == 0) {
minEven = min(minEven, alphabetFrequency[i]);
} else {
maxOdd = max(maxOdd, alphabetFrequency[i]);
}
}
}
return maxOdd - minEven;
}
};
complexity
- Time:
O(n)wherenis the size of the strings- Space:
O(1)since there are always a maximum of26letters we have to store the count for