본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 디펜스 게임(Java)

by hxxyeoniii 2024. 11. 12.

링크 : https://school.programmers.co.kr/learn/courses/30/lessons/142085

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제 풀이

* 우선순위 큐(PriorityQueue) 사용

// 작은 수가 먼저 나옴
PriorityQueue<Integer> pq = new PriorityQueue<>();
 
// 큰 수 먼저 나옴
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

: 들어가는 순서와 상관없이 우선순위가 높은 데이터가 먼저 나가는 자료구조

: 기본으로는 작은 수가 먼저 나옴

 

 

import java.util.*;

class Solution {
    public int solution(int n, int k, int[] enemy) {
        int answer = 0;
        
        PriorityQueue<Integer> pq = new PriorityQueue();
        
        for(int i=0; i<enemy.length; i++) {
            pq.add(enemy[i]);
            
            // 무적권을 먼저 사용
            if(pq.size() <= k) {
                answer++;
                continue;
            }
            
            n -= pq.poll();
            
            if(n < 0) {
                break;
            }
            
            answer++;
        }
        
        return answer;
    }
}