Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 3, 2025 22:54
Show Gist options
  • Select an option

  • Save Ifihan/ea3024783d8e07386f00e2653e8c9457 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/ea3024783d8e07386f00e2653e8c9457 to your computer and use it in GitHub Desktop.
Minimum Time to Make Rope Colorful

Question

Approach

I sweep the string left to right and treat each run of consecutive same-colored balloons as a group. To avoid adjacent equal colors I must remove all but one balloon in each group; the minimum cost for a group is the sum of its removal times minus the maximum time in that group. Equivalently, while scanning, whenever the current balloon has the same color as the previous one, I remove the cheaper of the two (add min(prev_time, cur_time) to the answer) and keep the larger time as the survivor for further comparisons.

Implementation

class Solution:
    def minCost(self, colors: str, neededTime: List[int]) -> int:
        total = 0
        prev_time = neededTime[0]
        for i in range(1, len(colors)):
            if colors[i] == colors[i-1]:
                total += min(prev_time, neededTime[i])
                prev_time = max(prev_time, neededTime[i])
            else:
                prev_time = neededTime[i]
        return total

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment