[프로그래머스] 신입사원 교육 (Python)

yuuforest·2023년 10월 3일

알고리즘

목록 보기
7/8
post-thumbnail

프로그래머스 문제 풀이 - PCCP 모의고사 #2

📰 문제


문제 확인 🏃


💡 입출력 예제


[10, 3, 7, 2], 2

>> 37
[1, 2, 3, 4], 3

>> 26

💬 풀이


🎵 첫번째 풀이 - 시간초과😥

def solution(ability, number):

    for _ in range(number):

        ability.sort(reverse=True)

        total = 0
        for _ in range(2):
            total += ability[-1]
            ability.pop()
        
        ability.append(total)
        ability.append(total)

    return sum(ability)

🎵 두번째 풀이

import heapq

def solution(ability, number):

    q = []
    for a in ability:
        heapq.heappush(q, a)

    for _ in range(number):

        total = 0
        for _ in range(2):
            total += heapq.heappop(q)
        
        heapq.heappush(q, total)
        heapq.heappush(q, total)

    return sum(q)

🎵 세번째 풀이 😇

from heapq import heappush, heappop

def solution(ability, number):

    q = []
    for a in ability:
        heappush(q, a)

    for _ in range(number):

        total = 0
        for _ in range(2):
            total += heappop(q)
        
        heappush(q, total)
        heappush(q, total)

    return sum(q)


✒️ 생각


우선순위 큐가 짱이야 진짜..

profile
🐥 Backend Developer 🐥

0개의 댓글