프로그래머스 더 맵게 (Java)

Kim Yongbin·2024년 4월 21일
post-thumbnail

문제

프로그래머스 - 더 맵게

Code

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public int solution(int[] scoville, int K) {
        int answer = 0;
        
        // 주어진 배열을 PriorityQueue에 담기
        PriorityQueue<Integer> pq = Arrays.stream(scoville)
            .boxed()
            .collect(Collectors.toCollection(PriorityQueue::new));
        
        // 앞에 2개씩 뽑으면서 음식 섞기
        while (pq.size() > 1 && pq.peek() < K){
            int f1 = pq.poll();
            int f2 = pq.poll();

            pq.add(f1 + f2 * 2);
            answer ++;
            
        }
        
        // 문제 조건 체크
        if (pq.peek() < K) return -1;
        else return answer;
    }
}
  • Arrays.stream(scoville).boxed().collect(Collectors.toCollection(PriorityQueue::new));
    • stream을 이용하여 PQ에 한번에 넣었다.
    • .boxed()
      • int → Integer로 감싸기
    • .collect(Collectors.toCollection(PriorityQueue::new))
      • PriorityQueue에 넣기
profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글