프로그래머스 - 힙 - 더 맵게

2021. 3. 21. 11:03Algorithm

programmers.co.kr/learn/courses/30/lessons/42626

 

코딩테스트 연습 - 더 맵게

매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같

programmers.co.kr

import java.util.PriorityQueue;

public class 더_맵게 {
    public static void main(String[] args) {
        더_맵게 o = new 더_맵게();
        System.out.println(o.solution(new int[]{1, 2, 3, 9, 10, 12}, 1000000000));
    }

    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for(int i=0; i<scoville.length; i++) {
            q.offer(scoville[i]);
        }

        int count = 0;
        while (q.peek() < K) {
            Integer food1 = q.poll();
            Integer food2 = q.poll();

            if(food2 == null) {
                return -1;
            }

            Integer newFood = food1 + (food2 * 2);
            q.offer(newFood);
            count++;
        }

        return count;
    }
}

 

알고리즘

  • 우선순위 큐 활용문제