1578. Minimum Time to Make Rope Colorful

1578. 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 i<sup>th</sup> 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 i<sup>th</sup> balloon from the rope.

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

Solution

滑动窗口,遍历字符串。
common用来记录连续颜色相同的个数,初始化为1。
如果当前字符与下一个字符相同,则窗口向右侧扩展,common++。
遍历时记录替换气球需要的最大时间maxTime和替换掉所有同色气球的总时间deleteTime。

如果common大于1,则总时间加上需要删除的时间(刨除最大时间maxTime)。
更新i为i + common。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int minCost(String colors, int[] neededTime) {
int i = 0, totalTime = 0;
char[] c = colors.toCharArray();
while(i < neededTime.length){
int common = 1, maxTime = neededTime[i], deleteTime = neededTime[i];
while(i + common < neededTime.length && c[i] == c[i + common]){
maxTime = Math.max(maxTime, neededTime[i + common]);
deleteTime += neededTime[i + common];
common++;
}
if(common > 1){
deleteTime -= maxTime;
totalTime += deleteTime;
}
i += common;
}
return totalTime;
}
}
Author

Xander

Posted on

2022-10-03

Updated on

2022-10-03

Licensed under

Comments