문제
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 ballons at indices 0 and 4. Each ballon 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.
풀이
우선 n 의 최댓값이 10의 5승이기 때문에 for 문을 여러번 돌기 부담스럽다.
나는 for 문을 한번만 돌며, 같은 풍선일 때 우선순위 큐에 모두 넣은 후,
다른 풍선을 만나거나 배열의 끝에 도달했을 때 작은 것부터 뺐다. 하나만 남기고.
합을 반환하면
끝.
힌트가
sum 과 max 를 계속 가져가라는 말에 출제자의 의도는 우선순위 큐를 사용하지 않아도 sum 을 계속 더한 후 max 를 뺀 값을 answer 에 더해 (결국 같은풍선의 합 - max 값 하나의 풍선이 빼야될 풍선의 값이므로) 풀도록 의도했다.
출제자의 의도대로도 한번 풀어보면 좋을 것 같다.
아래는 내 풀이
import heapq
from typing import List
class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
answer = 0
n = len(colors)
h = []
for i in range(n):
if i+1 < n and colors[i] == colors[i+1]:
if not h:
heapq.heappush(h,neededTime[i])
heapq.heappush(h,neededTime[i+1])
else:
while len(h) > 1:
answer += heapq.heappop(h)
h.clear()
return answer