Minimum Time to Make Rope Colorful - Problem

Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith 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 ith balloon from the rope.

Return the minimum time Bob needs to make the rope colorful.

Input & Output

Example 1 — Basic Group Removal
$ Input: colors = "aabaa", neededTime = [1,3,2,5,4]
Output: 5
💡 Note: First group 'aa' at positions 0-1: keep balloon with cost 3, remove balloon with cost 1. Last group 'aa' at positions 3-4: keep balloon with cost 5, remove balloon with cost 4. Total removal cost: 1 + 4 = 5.
Example 2 — Multiple Consecutive Groups
$ Input: colors = "aaabbbaaab", neededTime = [1,3,2,5,4,9,8,1,3,6]
Output: 21
💡 Note: Group 'aaa': keep cost 3, remove costs 1+2=3. Group 'bbb': keep cost 9, remove costs 5+4=9. Group 'aaa': keep cost 3, remove costs 8+1=9. Single 'b': keep cost 6. Total: 3+9+9=21 removal cost.
Example 3 — No Consecutive Same Colors
$ Input: colors = "abaca", neededTime = [1,2,3,4,5]
Output: 0
💡 Note: All balloons have different colors from their neighbors, so no removals needed.

Constraints

  • n == colors.length == neededTime.length
  • 1 ≤ n ≤ 105
  • 1 ≤ neededTime[i] ≤ 104
  • colors contains only lowercase English letters

Visualization

Tap to expand
Minimum Time to Make Rope Colorful INPUT a a b a a colors = "aabaa" 0 1 2 3 4 neededTime Array: 1 3 2 5 4 No two consecutive balloons same color Groups: [a,a] [b] [a,a] ALGORITHM STEPS 1 Find consecutive groups Scan for same colors 2 For each group: Keep max time balloon 3 Remove others in group Sum their times 4 Accumulate total cost Return minimum time Processing Groups: Group [a,a]: times [1,3] Keep 3, Remove 1 = +1 Group [b]: times [2] Single, skip = +0 Group [a,a]: times [5,4] Keep 5, Remove 4 = +5 FINAL RESULT a b a Colorful rope: "aba" Removed Balloons: a time=1 a time=4 X X Total Removal Time: 1 + 0 + 5 = 6 Output: 6 Key Insight: For each group of consecutive same-colored balloons, we must keep exactly ONE balloon. To minimize removal time, keep the balloon with MAXIMUM time (most expensive to remove), and remove all others. Cost = (sum of group times) - (max time in group). Time: O(n), Space: O(1) TutorialsPoint - Minimum Time to Make Rope Colorful | Greedy - Single Pass with Group Processing
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
89.5K Views
Medium Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen