3753. Maximum Difference Between Even And Odd Frequency I¶
Difficulty: Easy
LeetCode Problem View on GitHub
3753. 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 between the frequency of two characters in the string such that:
- One of the characters has an even frequency in the string.
- The other character has an odd frequency in the string.
Return the maximum difference, calculated as the frequency of the character with an odd frequency minus the frequency of the character with an even frequency.
Example 1:
Input: s = "aaaaabbc"
Output: 3
Explanation:
- The character
'a'has an odd frequency of5, and'b'has an even frequency of2. - The maximum difference is
5 - 2 = 3.
Example 2:
Input: s = "abcabcab"
Output: 1
Explanation:
- The character
'a'has an odd frequency of3, and'c'has an even frequency of 2. - The maximum difference is
3 - 2 = 1.
Constraints:
3 <= s.length <= 100sconsists only of lowercase English letters.scontains at least one character with an odd frequency and one with an even frequency.
Solution¶
class Solution {
public int maxDifference(String s) {
int n = s.length();
int freq[] = new int[26];
for (int i = 0; i < n; i++) freq[s.charAt(i) - 'a']++;
ArrayList<Integer> even = new ArrayList<>();
ArrayList<Integer> odd = new ArrayList<>();
for (int i = 0; i < 26; i++) {
if (freq[i] % 2 == 0 && freq[i] != 0) even.add(freq[i]);
else odd.add(freq[i]);
}
int maxi = Integer.MIN_VALUE;
for (int i = 0; i < odd.size(); i++) {
for (int j = 0; j < even.size(); j++) {
maxi = Math.max(maxi, odd.get(i) - even.get(j));
}
}
return maxi;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here