1578. Minimum Time to Make Rope Colorful #2375
-
|
Topics: Alice has Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array Return the minimum time Bob needs to make the rope colorful. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to ensure that no two consecutive balloons have the same color by removing some balloons. The goal is to minimize the total time required to remove these balloons. Approach
Let's implement this solution in PHP: 1578. Minimum Time to Make Rope Colorful <?php
/**
* @param String $colors
* @param Integer[] $neededTime
* @return Integer
*/
function minCost($colors, $neededTime) {
$n = strlen($colors);
$totalTime = 0;
$i = 0;
while ($i < $n) {
$currentColor = $colors[$i];
$currentMax = $neededTime[$i];
$currentSum = $neededTime[$i];
$j = $i + 1;
while ($j < $n && $colors[$j] == $currentColor) {
$currentSum += $neededTime[$j];
if ($neededTime[$j] > $currentMax) {
$currentMax = $neededTime[$j];
}
$j++;
}
$totalTime += $currentSum - $currentMax;
$i = $j;
}
return $totalTime;
}
// Test cases
$colors1 = "abaac";
$neededTime1 = array(1, 2, 3, 4, 5);
echo minCost($colors1, $neededTime1) . "\n"; // Output: 3
$colors2 = "abc";
$neededTime2 = array(1, 2, 3);
echo minCost($colors2, $neededTime2) . "\n"; // Output: 0
$colors3 = "aabaa";
$neededTime3 = array(1, 2, 3, 4, 1);
echo minCost($colors3, $neededTime3) . "\n"; // Output: 2
?>Explanation:
|
Beta Was this translation helpful? Give feedback.



We need to ensure that no two consecutive balloons have the same color by removing some balloons. The goal is to minimize the total time required to remove these balloons.
Approach