본문 바로가기
Programming/Python

[프로그래머스] 더 맵게

by 왕밤빵도라에몽 2025. 4. 2.
728x90

기본 아이디어

  • 힙큐
  • 하라는대로 구현
import heapq

def solution(scoville, K):
    heapq.heapify(scoville)
    count = 0
    while scoville:
        first = heapq.heappop(scoville)
        if first >= K:
            break
        if len(scoville) == 0:
            return -1
        new = first + heapq.heappop(scoville) * 2
        heapq.heappush(scoville, new)
        count += 1

    return count
  • heapq.heapify는 리스트를 힙으로 바꿔서 반환하는 것이 아니라, 리스트 자체를 힙으로 정렬함. (그니까 반환값 None)
  • 중간에 scville을 모두 K 이상으로 만들 수 없는 경우를 예외처리 해줘야 함.
728x90

'Programming > Python' 카테고리의 다른 글

[백준] 2606 | 바이러스  (0) 2025.04.07
[프로그래머스] 게임 맵 최단거리  (0) 2025.04.07
[프로그래머스] 타겟 넘버  (0) 2025.04.02
[프로그래머스] K번째 수  (0) 2025.04.02
[프로그래머스] 체육복  (0) 2025.03.27