[프로그래머스] 더맵게 (python)

Baedonguri·2022년 5월 7일
0
post-thumbnail

https://programmers.co.kr/learn/courses/30/lessons/42626

답안 코드

최소힙을 이용하면 어렵지 않게 풀 수 있는 문제이다.

from heapq import heapify, heappop, heappush
def solution(scoville, K):
    heapify(scoville) #scoville 리스트를 heap으로 만든다

    answer = 0 # 섞은 횟수를 저장할 변수
    while True:
        try: 
            first = heappop(scoville) # scoville에서 최소값을 꺼냄(가장 맵지 않은 음식)
            if first >= K: return answer # 꺼낸 값이 K보다 같거나 크다면 뒤의 요소들은 무조건 K 이상이므로 종료
            mix = first + (heappop(scoville)*2) # 가장 맵지 않은 음식과 두번째로 맵지 않은 음식의 스코빌 지수 섞기
            heappush(scoville,mix) # 섞은 값을 scoville에 다시 넣어줌
            answer += 1 # 섞은 횟수 + 1 해주기
        except: # 모든 음식을 K이상으로 만들 수 없는 경우에 -1을 리턴
            return -1
profile
Software Engineer

0개의 댓글