Programming/Python

[Python3] 프로그래머스 - 더 맵게(Heap)

아나엘 2023. 10. 22. 02:57

효율성에서 계속 걸렸는데 while문에서 min(scoville) 나 heapq.nsmallest(scoville, 1) 했던걸 scoville[0] 하니까 통과됐다!

import heapq

def solution(scoville, K):
    answer = 0
    scoville.sort()
    if scoville[0]>=K:
        return 0
    heapq.heapify(scoville)

    while scoville[0]<K:
        if len(scoville)==1:
            answer=-1
            break
        heapq.heappush(scoville,heapq.heappop(scoville)+(heapq.heappop(scoville)*2))
        answer+=1

    return answer
반응형