[프로그래머스] Level 2. 힙(Heap) > 더 맵게 (Java)

emz·2022년 2월 22일
0

Programmers

목록 보기
1/2

문제링크

더 맵게


구현코드

import java.util.PriorityQueue;

class Solution {
    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(); // 스코빌 지수를 담을 우선순위 큐
        int answer = 0; // 음식을 섞는 횟수
        
        for(int s : scoville){
            pq.offer(s);
        }
        
        while(pq.size() > 1 && pq.peek() < K) {
        	pq.offer(pq.poll() + (pq.poll() * 2)); // 섞은 음식의 스코빌 지수 담아주기
        	answer++; 
        }

        return pq.peek() >= K ? answer : -1; // 모든 음식의 스코빌 지수를 k 이상으로 만들 수 없는 경우 -1 리턴
    }
}
profile
끄적끄적

0개의 댓글