← All problems

3442. Maximum Difference Between Even and Odd Frequency I

EasyOpen on LeetCodeProblem statement

Problem Statement

3442. Maximum Difference Between Even and Odd Frequency I

Easy


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:

Return this maximum difference.

 

Example 1:

Input: s = "aaaaabbc"

Output: 3

Explanation:

Example 2:

Input: s = "abcabcab"

Output: 1

Explanation:

 

Constraints:

Java

Source file
class Solution {
    public int maxDifference(String s) {
        int[] freq = new int[26];
        for (char c : s.toCharArray())
            freq[c - 'a']++;
        int maxOdd = -1, minEven = Integer.MAX_VALUE;
        for (int i = 0; i < 26; i++) {
            if (freq[i] == 0)
                ;
            else if ((freq[i] & 1) == 1)
                maxOdd = Math.max(maxOdd, freq[i]);
            else
                minEven = Math.min(minEven, freq[i]);
        }
        // System.out.println(maxOdd + "\t" + minEven);
        return maxOdd - minEven;
    }
}