[프로그래머스_42626] 더 맵게 Python 풀이

출처: 프로그래머스

문제

image

풀이

heap을 이용하여 풀어주었습니다.

주어진 scoville을 heapify해주고, 두 번의 heappop을 해주어야 하기 때문에 while문의 조건을 scoville의 길이가 2 이상인 경우와, scoville의 가장 작은 원소가 K보다 작을 때, 즉 아직 주어진 K보다 작은 스코빌 지수를 가진 음식이 있을 경우로 해주었습니다.

각각 두 번의 heappop으로 가장 낮은 lowest와, 두 번째로 낮은 second로 연산한 값을 다시 heappush로 넣어주었고, answer도 1 증가시켜줍니다.

끝까지 섞어주어도 K보다 낮을 경우에는 -1을 return하고 그렇지 않을 경우에만 answer를 return합니다.

코드

from heapq import heapify, heappush, heappop
def solution(scoville, K):
    answer = 0
    heapify(scoville)
    while len(scoville) >= 2 and scoville[0] < K:
        lowest = heappop(scoville)
        second = heappop(scoville)
        answer += 1
        heappush(scoville, lowest+second*2)
    return answer if scoville[0] >= K else -1

Leave a comment