3445. Maximum Difference Between Even and Odd Frequency II #1793
-
Topics: You are given a string
Return the maximum difference. Note that Example 1:
Example 2:
Example 3:
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 two characters,
Approach
Let's implement this solution in PHP: 3445. Maximum Difference Between Even and Odd Frequency II <?php
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function maxDifference($s, $k) {
$chars = array('0', '1', '2', '3', '4');
$permutations = array();
foreach ($chars as $a) {
foreach ($chars as $b) {
if ($a != $b) {
$permutations[] = array($a, $b);
}
}
}
$ans = PHP_INT_MIN;
$n = strlen($s);
foreach ($permutations as $pair) {
$a = $pair[0];
$b = $pair[1];
$prefixA = array(0);
$prefixB = array(0);
$minDiff = array(
array(PHP_INT_MAX, PHP_INT_MAX),
array(PHP_INT_MAX, PHP_INT_MAX)
);
$l = 0;
for ($r = 0; $r < $n; $r++) {
$lastA = end($prefixA);
$lastB = end($prefixB);
$char = $s[$r];
$nextA = $lastA + ($char == $a ? 1 : 0);
$nextB = $lastB + ($char == $b ? 1 : 0);
array_push($prefixA, $nextA);
array_push($prefixB, $nextB);
while (($r - $l + 1) >= $k &&
$prefixA[$l] < end($prefixA) &&
$prefixB[$l] < end($prefixB)) {
$pA = $prefixA[$l] % 2;
$pB = $prefixB[$l] % 2;
$diff = $prefixA[$l] - $prefixB[$l];
if ($diff < $minDiff[$pA][$pB]) {
$minDiff[$pA][$pB] = $diff;
}
$l++;
}
$curA = end($prefixA);
$curB = end($prefixB);
$stateA = 1 - ($curA % 2);
$stateB = $curB % 2;
$candidate = ($curA - $curB) - $minDiff[$stateA][$stateB];
if ($candidate > $ans) {
$ans = $candidate;
}
}
}
return $ans;
}
// Test cases
echo maxDifference("12233", 4) . "\n"; // Output: -1
echo maxDifference("1122211", 3) . "\n"; // Output: 1
echo maxDifference("110", 3) . "\n"; // Output: -1
?> Explanation:
This approach efficiently narrows down the problem to manageable computations by leveraging sliding windows, prefix sums, and state enumeration, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum difference between the frequency of two characters,
a
andb
, in any substring of the given strings
such that:k
.a
is odd.b
is even.Approach
Problem Analysis: The problem requires examining all possible substrings of
s
with length at leastk
to find the maximum difference between the frequency of a character with an odd count and another character with an even count. Given the constraints, a brute-force approach is infeasible. Instead, we use a sliding window technique combined with prefix sums and state enumeration for efficiency.Key Insight: For each pair of d…