Minimum Time to Make Rope Colorful Problem
Description
LeetCode Problem 1578.
Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i^th balloon.
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 neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i^th balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
Example 1:

Input: colors = "abaac", neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:

Input: colors = "abc", neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:

Input: colors = "aabaa", neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
n == colors.length == neededTime.length1 <= n <= 10^51 <= neededTime[i] <= 10^4colorscontains only lowercase English letters.
Solution
Approach: Keep the Slowest Balloon of Each Run
Two balloons interact only if they are next to each other with the same color, so the rope splits into maximal runs of one color, and each run can be handled on its own.
Inside a run, all balloons but one must go, since any two that stay would end up next to each other. Keeping one balloon per run is also enough: it stays between the neighboring runs, so they never touch each other. The cheapest choice is to keep the balloon that takes the longest to remove.
For each run, the cost is therefore the sum of its neededTime values minus their maximum. Two pointers find the runs: i marks the start, and j walks forward while the color stays the same. A run of length one costs nothing.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
n = len(colors)
total = i = 0
while i < n:
# colors[i..j-1] is a run of one color: keep its slowest balloon, remove the rest
j = i
run_sum = run_max = 0
while j < n and colors[j] == colors[i]:
run_sum += neededTime[j]
run_max = max(run_max, neededTime[j])
j += 1
total += run_sum - run_max
i = j
return total