LeetCode 1578. Minimum Time to Make Rope Colorful Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1578. Minimum Time to Make Rope Colorful

Description

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 balloons at indices 0 and 4. Each balloons 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.

Solutions

Solution 1: Two Pointers + Greedy

We can use two pointers to point to the beginning and end of the current consecutive balloons with the same color, then calculate the total time s of these consecutive balloons with the same color, as well as the maximum time mx. If the number of consecutive balloons with the same color is greater than 1, we can greedily choose to keep the balloon with the maximum time and remove the other balloons with the same color, which takes time s - mx, and add it to the answer. Then we continue to traverse until all balloons are traversed.

The time complexity is O(n) and the space complexity is O(1), where n is the number of balloons.

PythonJavaC++GoTypeScriptRust
class Solution: def minCost(self, colors: str, neededTime: List[int]) -> int: ans = i = 0 n = len(colors) while i < n: j = i s = mx = 0 while j < n and colors[j] == colors[i]: s += neededTime[j] if mx < neededTime[j]: mx = neededTime[j] j += 1 if j - i > 1: ans += s - mx i = j return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !