Minimum Time to Make Rope Colorful
Medium · Greedy · Explanation and code example
Two Pointers - III
How it works
We can simplify the logic further by tracking the maximum removal time seen so far in the current group of same-colored balloons. For each balloon, we add the minimum of the current maximum and the current balloon's time to the result, then update the maximum. When we encounter a different color, we reset the maximum to 0.
Steps
- Initialize
res = 0andmaxi = 0. - For each index
i:- If
i > 0andcolors[i] != colors[i-1], resetmaxi = 0. - Add
min(maxi, neededTime[i])tores. - Update
maxi = max(maxi, neededTime[i]).
- If
- Return
res.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)extra space.
Things to watch for
Removing the Wrong Balloon
When encountering consecutive same-colored balloons, some may instinctively remove the first balloon encountered or remove all of them. The correct strategy is to keep the balloon with the maximum removal time and remove all others, minimizing total cost.
Forgetting to Reset State Between Groups
When processing groups of consecutive same-colored balloons, failing to reset the maximum or sum tracking variables when transitioning to a new color group leads to incorrect calculations. Each group must be processed independently.
Off-by-One Errors in Group Boundaries
When using two pointers to identify groups of consecutive balloons, it is easy to mishandle the boundary conditions, either including an extra balloon from the next group or missing the last balloon in the current group. Carefully ensure the inner loop condition correctly identifies when colors change.
Python code example
from typing import List
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
res = maxi = 0
for i in range(len(colors)):
if i and colors[i] != colors[i - 1]:
maxi = 0
res += min(maxi, neededTime[i])
maxi = max(maxi, neededTime[i])
return res
C++ code example
class Solution {
public:
int minCost(string colors, vector<int>& neededTime) {
int res = 0, maxi = 0;
for (int i = 0; i < colors.size(); i++) {
if (i > 0 && colors[i] != colors[i - 1]) {
maxi = 0;
}
res += min(maxi, neededTime[i]);
maxi = max(maxi, neededTime[i]);
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.