목차

더 맵게

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호42626
문제명더 맵게
레벨Level 2
분류

시간복잡도O(nlogn)
인풋사이즈n<=1,000,000
사용한 언어Python
해결날짜2021/05/28
태그

고득점 Kit - 힙(Heap)

풀이

코드

코드 1 - 힙을 사용

"""Solution code for "Programmers 42626. 더 맵게".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/42626
- Solution link: http://www.teferi.net/ps/problems/programmers/42626
"""

import heapq


def solution(scoville, K):
    heapq.heapify(scoville)
    for i in range(len(scoville) - 1):
        min_scov = heapq.heappop(scoville)
        if min_scov >= K:
            return i
        new_scov = min_scov + scoville[0] * 2
        heapq.heapreplace(scoville, new_scov)
    return i + 1 if scoville[0] >= K else -1

코드 2 - deque를 사용

"""Solution code for "Programmers 42626. 더 맵게".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/42626
- Solution link: http://www.teferi.net/ps/problems/programmers/42626
"""

import collections

INF = float('inf')


def solution(scoville, K):
    def pop_min():
        min_orig = orig_scovilles[-1] if orig_scovilles else INF
        min_new = new_scovilles[0] if new_scovilles else INF
        if min_orig < min_new:
            return orig_scovilles.pop()
        else:
            return new_scovilles.popleft()

    orig_scovilles = sorted(scoville, reverse=True)
    new_scovilles = collections.deque()

    for i in range(len(scoville) - 1):
        min_scov = pop_min()
        if min_scov >= K:
            return i
        second_min_scov = pop_min()
        new_scov = min_scov + second_min_scov * 2
        new_scovilles.append(new_scov)
    return i + 1 if new_scovilles[0] >= K else -1