3442. Maximum Difference Between Even and Odd Frequency I #1788
-
Topics: You are given a string Your task is to find the maximum
Return this maximum difference. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum difference between the frequency of a character with an odd frequency and a character with an even frequency in a given string. The solution involves counting the frequencies of each character, categorizing them based on whether their frequencies are odd or even, and then computing the maximum difference between the highest odd frequency and the lowest even frequency. Approach
Let's implement this solution in PHP: 3442. Maximum Difference Between Even and Odd Frequency I <?php
/**
* @param String $s
* @return Integer
*/
function maxDifference($s) {
$freq = array_count_values(str_split($s));
$odd_freqs = [];
$even_freqs = [];
foreach ($freq as $count) {
if ($count % 2 == 1) {
$odd_freqs[] = $count;
} else {
$even_freqs[] = $count;
}
}
$max_odd = max($odd_freqs);
$min_even = min($even_freqs);
return $max_odd - $min_even;
}
// Example 1
$s1 = "aaaaabbc";
echo "Input: $s1\n";
echo "Output: " . maxDifference($s1) . "\n"; // Output: 3
// Example 2
$s2 = "abcabcab";
echo "Input: $s2\n";
echo "Output: " . maxDifference($s2) . "\n"; // Output: 1
?> Explanation:
This approach efficiently categorizes the frequencies and leverages simple arithmetic operations to derive the solution, ensuring optimal performance with a time complexity of O(n), where n is the length of the string. The space complexity is O(1) since the number of distinct characters is bounded by the alphabet size (26 lowercase English letters). |
Beta Was this translation helpful? Give feedback.
We need to find the maximum difference between the frequency of a character with an odd frequency and a character with an even frequency in a given string. The solution involves counting the frequencies of each character, categorizing them based on whether their frequencies are odd or even, and then computing the maximum difference between the highest odd frequency and the lowest even frequency.
Approach