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.
Example 1:

Input: colors = “abaac”, neededTime = [1,2,3,4,5]
Output: 3
Explanation: In the above image, ‘a’ is blue, ‘b’ is red, and ‘c’ is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.
Example 2:

Input: colors = “abc”, neededTime = [1,2,3]
Output: 0
Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.
Example 3:

Input: colors = “aabaa”, neededTime = [1,2,3,4,1]
Output: 2
Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
Constraints:
- n == colors.length == neededTime.length
- 1 <= n <= 105
- 1 <= neededTime[i] <= 104
- colors contains only lowercase English letters.
我们把连续的相同颜色的气球看做是一组, 一组里最终只能留下来一个气球, 而这个气球一定是这组气球里耗时最长的那个, 而实际移除所用的耗时,是这组气球全部移除所需要的耗时减去这个保留的气球。 然后剩下的事就非常简单了, 建两个变量分别维护当前该组的最大耗时和总耗时,遇到不同颜色的气球时, 结算前一组的耗时。
impl Solution {
pub fn min_cost(colors: String, needed_time: Vec<i32>) -> i32 {
let mut prev = colors.chars().nth(0).unwrap();
let mut max = needed_time[0];
let mut sum = needed_time[0];
let mut ans = 0;
for (i, c) in colors.chars().enumerate().skip(1) {
if c == prev {
max = max.max(needed_time[i]);
sum += needed_time[i];
continue;
}
ans += sum - max;
sum = needed_time[i];
max = needed_time[i];
prev = c;
}
ans += sum - max;
ans
}
}

本文介绍了一个有趣的编程问题:如何计算最小的时间成本来移除连续相同颜色的气球,使得绳子上的气球颜色变得多彩。通过遍历颜色字符串并跟踪最大时间和总时间,可以有效地解决这个问题。

被折叠的 条评论
为什么被折叠?



