3442. Maximum Difference Between Even and Odd Frequency I
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 <= 100
s
consists only of lowercase English letters.s
contains at least one character with an odd frequency and one with an even frequency.
Solution:
class Solution {
public int maxDifference(String s) {
int[] cnt = new int[26];
for (char b : s.toCharArray()){
cnt[b - 'a']++;
}
int max1 = 0;
int min0 = Integer.MAX_VALUE;
for (int c : cnt){
if (c % 2 > 0){
max1 = Math.max(max1, c);
}else if (c > 0){
min0 = Math.min(min0, c);
}
}
return max1 - min0;
}
}
class Solution {
public int maxDifference(String s) {
char[] sArray = s.toCharArray();
// a a a a a b b c
// i
//
Map<Character, Integer> map = new HashMap<>();
int maxOdd = 0;
int minOdd = Integer.MAX_VALUE;
int maxEven = 0;
int minEven = Integer.MAX_VALUE;
int n = s.length(); // 8
for (int i = 0; i < n; i++){//
char cur = sArray[i];// a
map.put(cur, map.getOrDefault(cur, 0) + 1);
// a
// int fre = map.get(cur); // 1
// if (fre % 2 == 0){
// maxEven = Math.max(maxEven, fre);
// minEven = Math.min(minEven, fre);
// }else{
// maxOdd = Math.max(maxOdd, fre);// 1
// minOdd = Math.min(minOdd, fre);// 0
// }
}
Set<Integer> set = new HashSet<>();
for (Map.Entry<Character, Integer> e : map.entrySet()){
int fre = e.getValue();
if (fre % 2 == 0){
maxEven = Math.max(maxEven, fre);
minEven = Math.min(minEven, fre);
}else{
maxOdd = Math.max(maxOdd, fre);// 1
minOdd = Math.min(minOdd, fre);// 0
}
}
int result = maxOdd - minEven;
// int result2 = minOdd - maxEven;
// if (Math.abs(result) < Math.abs(result2)){
// return result2;
// }else{
// return result;
// }
return result;
// return result;
}
}