Skip to content

3442. Maximum Difference Between Even and Odd Frequency I

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int maxDifference(string s) {
    vector<int> count(26);
    int maxOdd = 0;
    int minEven = s.length();

    for (const char c : s)
      ++count[c - 'a'];

    for (const int freq : count) {
      if (freq == 0)
        continue;
      if (freq % 2 == 0)
        minEven = min(minEven, freq);
      else
        maxOdd = max(maxOdd, freq);
    }

    return maxOdd - minEven;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int maxDifference(String s) {
    int[] count = new int[26];
    int maxOdd = 0;
    int minEven = s.length();

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    for (final int freq : count) {
      if (freq == 0)
        continue;
      if (freq % 2 == 0)
        minEven = Math.min(minEven, freq);
      else
        maxOdd = Math.max(maxOdd, freq);
    }

    return maxOdd - minEven;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def maxDifference(self, s: str) -> int:
    count = collections.Counter(s)
    maxOdd = max((freq for freq in count.values()
                  if freq % 2 == 1), default=0)
    minEven = min((freq for freq in count.values()
                   if freq % 2 == 0), default=len(s))
    return maxOdd - minEven