{% hint style="info" %} There is are approaches that uses #two-pointers or greedy instead but I will not cover those. {% endhint %}
Consecutive balloons do not count the popped balloons, so popping the middle R
in RRR
will still violate the criteria of having no consecutive colors.
Let's start with an arbitrary rope with balloons: RRRGGBB
and an arbitrary cost of [2, 1, 5, 3, 4, 1, 2]
. From hand-simulation, we know that the ultimate "optimal" answer is XXRXGBX
where X
are the popped balloons.
- For every segment of like colors, we never pop the highest cost balloon to achieve the lowest possible cost within the segment (the mathematical proof is relatively easy to come up with)
- When encountering a same color, a decision between popping the current balloon or the previously seen, unpopped, same balloon should be made, with the decision made to be the smallest of the two (see (1))
- For every segment of same color, once a balloon encountered is of a different color, there's no need to pop anymore of the previous color so the color tracked can be changed
prev
is needed alongside the recurrence.
Processing from left to right,
If
If
We will apply the
def min_time(r, time):
n = len(time)
t = 0
prev = 0
for i in range(1, n):
if r[i] == r[prev]:
t += min(time[i], time[prev])
if time[prev] < time[i]:
prev = i # since we pop the prev balloon, we have a new prev
else:
prev = i # we don't need to track the same color anymore
return t