[프로그래머스] 코딩테스트 연습 - 힙(Heap) Level 2 더 맵게

uoahy·2021년 9월 14일
0

Solution.java

import java.util.*;

class Solution {
    public int solution(int[] scoville, int K) {
        int answer = 0;
        
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        
        for (int s : scoville) {
            pq.add(s);
        }
        
        int[] min = new int[2];
        while (pq.size() >= 2 && pq.peek() < K) {
            min[0] = pq.poll();
            min[1] = pq.poll();
            
            pq.add(min[0] + min[1] * 2);
            
            answer++;
        }
        
        return pq.peek() < K ? -1 : answer;
    }
}

우선순위 큐를 이용하면 쉽게 풀 수 있는 문제였다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글