본문 바로가기
자료구조 & 알고리즘/문제풀이

더 맵게 - 프로그래머스 (Java, Level 2)

by 넬준 2022. 2. 9.

 

import java.util.PriorityQueue;

public class Solution {
	public int solution(int[] scoville, int K) {
        int answer = 0;
        //배열 값 중에서 첫번째, 두번째 작은 수를 찾아야 하므로
        //우선순위 큐 사용
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        
        for(int num : scoville) {
        	pq.add(num);
        }
        
        while(pq.size()>1 && pq.peek()<K) {
	        int minimum = pq.poll();
	        pq.add(minimum + pq.poll()*2);
	        answer++;
        }
        if(pq.peek()<K) answer = -1;
        
        return answer;
    }
}

댓글