[프로그래머스] 더 맵게

yjseo·2024년 9월 23일

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

틀린 풀이)

def solution(scoville, K):
    def recurse(foods, cnt):
        foods.sort()
        
        isSuccess = True
        for f in foods: 
            if f < K:
                isSuccess = False
                break
        
        if isSuccess:
            return cnt
        else:
            newfoods = [0] * (len(foods) - 1)
            newfoods[0] = foods[0] + foods[1] * 2
            for i in range(2, len(foods)):
                newfoods[i - 1] = foods[i]
            return recurse(newfoods, cnt + 1)
        
        return -1
    
    answer = recurse(scoville, 0)
        
    return answer

옳은 풀이)

import heapq

def solution(scoville, K):
    heapq.heapify(scoville)
    cnt = 0
    
    while scoville[0] < K:
        if len(scoville) < 2:
            return -1
        
        nfood = heapq.heappop(scoville) + (heapq.heappop(scoville) * 2)
        heapq.heappush(scoville, nfood)
        cnt += 1
    
    answer = cnt
    return answer

참고
https://gmlwjd9405.github.io/2018/05/10/data-structure-heap.html

profile
저 뭐해먹고 살아요..🥺

0개의 댓글