#1578
Medium Algorithms Minimum time to make rope colorful
Array String Dynamic Programming Greedy
65.2% acceptance
Feb 25, 2026
4335
156
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn min_cost(colors: String, needed_time: Vec<i32>) -> i32 {
let chars: Vec<char> = colors.chars().collect();
let n = chars.len();
let mut total = 0;
let mut i = 0;
while i < n {
let mut j = i;
// Find the group of consecutive same-color balloons
while j < n && chars[j] == chars[i] {
j += 1;
}
// Keep the max, remove all others
let group = &needed_time[i..j];
let sum: i32 = group.iter().sum();
let max_val: i32 = *group.iter().max().unwrap_or(&0);
total += sum - max_val;
i = j;
}
total
}
}