LeetCode 1578 Solution
Minimum Time to make rope colorful
#greedy #medium
Alice hasn
balloons arranged on a rope. You are given a 0-indexed stringcolors
wherecolors[i]
is the color of theith
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 arrayneededTime
whereneededTime[i]
is the time (in seconds) that Bob needs to remove theith
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.
python
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
result = 0
flag = None
record = []
for c, t in zip(colors, neededTime):
if c != flag:
if record:
result += sum(record) - max(record)
record = [t]
flag = c
else:
record.append(t)
if record:
result += sum(record) - max(record)
return result
The consecutive block of colors needs to be minimized to just one color and one neededTime
. So if the flag
is same as the front parts of colors, just append it to the record and flag continues. But if the flag differentialize part appear, sum(record) - max(record)
execute and reinitialize the flag and record.
if record
check whether the record list is empty or not. If it's empty, it means that the record is reinitialized and needs to be full with current colors.
As the solution search zipped list for just one time and search all not just needed part, it is greedy algorithm. And time and space complexity of this code is both $O(n)$.