Algorithm (PS)

[Programmers] 더 맵게 - Python

minjiwoo 2023. 5. 20. 12:23
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

heap 을 사용해서 효율적으로 푸는 것이 중요했던 문제 !! 

 

import heapq


def solution(scoville, K):
    answer = 0
    queue = []
    
    # 초기 힙큐 구성
    for i in scoville:
        heapq.heappush(queue, i)
   
    while queue[0] < K:

        heapq.heappush(queue, heapq.heappop(queue) + heapq.heappop(queue) * 2)


        answer += 1  # 섞는 횟수 + 1
        
        # 예외 처리 K 이상이 안되는 경우 
        if len(queue) == 1 and queue[0] < K:
            return -1 
    return answer
728x90