스터디/99클럽 코테 스터디 TIL

99클럽 코테 스터디 38일차 디펜스 게임

Been 2024. 8. 29. 10:36

📝 문제

 

프로그래머스

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

programmers.co.kr

 

🔥 시도해본 접근 방식

import java.util.*;

class Solution {

    public int solution(int n, int k, int[] enemy) {
        
        int soldier = n;
        int passCard = k;
        
        PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
        
        int roundIndex = 1;
        for (int round : enemy) {
            queue.add(round);
            soldier -= round;
            
            if (soldier < 0) {
                while (!queue.isEmpty()) {
                    if (passCard == 0) {
                        break;
                    }

                    soldier += queue.poll();
                    passCard--;
                    
                    if (soldier >= 0) {
                        break;
                    }
                }
            }
            
            if (soldier < 0) {
                return roundIndex - 1;
            }
            
            roundIndex++;
        }
            
        return enemy.length;
    }
}