We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Time to Make Rope Colorful

Number: 1700

Difficulty: Medium

Paid? No

Companies: Microsoft, Amazon


Problem Description

Given a string representing the colors of balloons arranged on a rope and an array representing the time needed to remove each balloon, the goal is to remove the minimum total time such that no two consecutive balloons have the same color.


Key Insights

  • Use a greedy approach by scanning the string.
  • For each group of consecutive balloons with the same color, keep the balloon with the maximum removal time and remove the rest.
  • The time cost for each group is the sum of removal times minus the maximum removal time in that group.
  • This ensures that only one balloon from each group remains, thereby satisfying the condition.

Space and Time Complexity

Time Complexity: O(n) - A single pass through the array. Space Complexity: O(1) - Constant additional space is used.


Solution

We iterate through the colors string while tracking a group of consecutive balloons that have the same color. For each group:

  1. Sum the total removal time.
  2. Identify the balloon with the maximum removal time.
  3. The cost to remove the extra balloons in the group is the total time minus the maximum.
  4. Add this cost to the overall minimum removal time. This greedy approach ensures that we remove the balloons with the least removal times while keeping the one with the highest removal cost to maximize savings.

Code Solutions

# Python solution

def minCost(colors, neededTime):
    # Initialize total time to 0
    total_time = 0
    n = len(colors)
    i = 0
    # Iterate over the entire string
    while i < n:
        curr_color = colors[i]
        group_sum = 0
        group_max = 0
        # Process the group of same colored balloons
        while i < n and colors[i] == curr_color:
            group_sum += neededTime[i]
            group_max = max(group_max, neededTime[i])
            i += 1
        # Remove all but the one balloon with the maximum removal time in the group
        total_time += group_sum - group_max
    return total_time

# Example usage:
print(minCost("abaac", [1,2,3,4,5]))  # Output: 3
← Back to All Questions