The goal is to remove consecutive balloons of the same color such that no two adjacent balloons share a color. When we find a group of consecutive same-colored balloons, we need to keep exactly one and remove the rest. To minimize the total removal time, we should keep the balloon with the highest removal cost and remove all others.
res = 0 and i = 0.i < n:i.curr) and the maximum removal time (maxi) in this group.curr - maxi to res (we keep the most expensive one, remove the rest).i to the next group.res as the result.class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
n = len(neededTime)
res = i = 0
while i < n:
j = i
maxi = curr = 0
while j < n and colors[j] == colors[i]:
maxi = max(maxi, neededTime[j])
curr += neededTime[j]
j += 1
res += curr - maxi
i = j
return resInstead of finding entire groups at once, we can process pairs of adjacent balloons. When two adjacent balloons have the same color, we remove the one with smaller removal time. We keep a pointer l to track the balloon we're keeping, and compare it with each new balloon at position r.
l = 0 and res = 0.r from 1 to n-1:colors[l] == colors[r] (same color):neededTime[l] < neededTime[r]: add neededTime[l] to res and update l = r.neededTime[r] to res (keep l unchanged).l = r.res.We can simplify the logic further by tracking the maximum removal time seen so far in the current group of same-colored balloons. For each balloon, we add the minimum of the current maximum and the current balloon's time to the result, then update the maximum. When we encounter a different color, we reset the maximum to 0.
res = 0 and maxi = 0.i:i > 0 and colors[i] != colors[i-1], reset maxi = 0.min(maxi, neededTime[i]) to res.maxi = max(maxi, neededTime[i]).res.When encountering consecutive same-colored balloons, some may instinctively remove the first balloon encountered or remove all of them. The correct strategy is to keep the balloon with the maximum removal time and remove all others, minimizing total cost.
When processing groups of consecutive same-colored balloons, failing to reset the maximum or sum tracking variables when transitioning to a new color group leads to incorrect calculations. Each group must be processed independently.
When using two pointers to identify groups of consecutive balloons, it is easy to mishandle the boundary conditions, either including an extra balloon from the next group or missing the last balloon in the current group. Carefully ensure the inner loop condition correctly identifies when colors change.