1717. Maximum Score From Removing Substrings #1960
-
Topics: You are given a string
Return the maximum points you can gain after applying the above operations on Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's the step-by-step implementation in PHP:
Here's the implementation in PHP: <?php
class Solution {
/**
* @param String $s
* @param Integer $x
* @param Integer $y
* @return Integer
*/
function maximumGain($s, $x, $y) {
if ($x < $y) {
// Swap the operations to always handle the higher value first
$temp = $x;
$x = $y;
$y = $temp;
$s = str_replace('a', 'temp', $s);
$s = str_replace('b', 'a', $s);
$s = str_replace('temp', 'b', $s);
}
// Remove 'ab' first since x >= y
list($score1, $remainingStr) = $this->calculatePoints($s, 'ab', $x);
// Remove 'ba' from the remaining string
list($score2, $remainingStr) = $this->calculatePoints($remainingStr, 'ba', $y);
return $score1 + $score2;
}
// Function to calculate points for the given string and operations
function calculatePoints($s, $sub, $points) {
$stack = [];
$score = 0;
foreach (str_split($s) as $char) {
if (!empty($stack) && $char == $sub[1] && end($stack) == $sub[0]) {
array_pop($stack);
$score += $points;
} else {
$stack[] = $char;
}
}
return [$score, implode('', $stack)];
}
}
// Remove 'ab' first since x >= y
list($score1, $remainingStr) = calculatePoints($s, 'ab', $x);
// Remove 'ba' from the remaining string
list($score2, $remainingStr) = calculatePoints($remainingStr, 'ba', $y);
return $score1 + $score2;
}
// Example usage
$s = "cdbcbbaaabab";
$x = 4;
$y = 5;
echo maximumGain($s, $x, $y); // Output: 19
$s = "aabbaaxybbaabb";
$x = 5;
$y = 4;
echo maximumGain($s, $x, $y); // Output: 20
?> Explanation:
This ensures that you get the maximum possible score by prioritizing the removal of higher-value substrings first. |
Beta Was this translation helpful? Give feedback.
Here's the step-by-step implementation in PHP:
Determine the order of removal: It is crucial to decide the order of removing "ab" and "ba". If
x > y
, it is better to remove "ab" first, otherwise, remove "ba" first. This is because removing the more valuable substring first maximizes the score.Use a stack to process the string: By using a stack, you can efficiently manage the removals. You push characters onto the stack and check the top of the stack to see if you can remove the desired substring.
Here's the implementation in PHP: