알고리즘/프로그래머스

[프로그래머스/JAVA] 더 맵게

092 2024. 4. 1. 13:02
문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42626
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 내용 : 아래 더보기

 

정답 코드 ) 최소힙 사용
import java.util.*;

class Solution {
    public int solution(int[] scoville, int K) {
        // 매번 sort하지 않아도, min 값을 유지하려면 => min 힙 사용
        Queue<Integer> list = new PriorityQueue<>();
        
        for(int s : scoville) list.offer(s);
        
        int answer = 0; // 스코빌 지수를 섞은 횟수
        
        while(list.size() >= 2 && list.peek() < K) {
            int n1 = list.poll();
            int n2 = list.poll();
            int n3 = n1 + n2 * 2;
            list.offer(n3);
            answer++;
        }
        
        if(list.peek() < K ) return - 1;
        
        return answer;
    }
}