![[프로그래머스] 디펜스 게임 - LV 2](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FIvq6N%2FbtsMfYVBqz8%2FWT0TrwK2UfzKH9OsY20yw0%2Fimg.png)
[프로그래머스] 디펜스 게임 - LV 2프로그래머스2025. 2. 12. 14:02
Table of Contents
📝 문제
https://school.programmers.co.kr/learn/courses/30/lessons/142085
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
🔑 풀이
import java.util.*;
class Solution {
public int solution(int n, int k, int[] enemy) {
int answer = 0;
// PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // 내림차순
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int e : enemy) {
pq.add(-e); // 내림차순
// 무적권을 사용하는 상황
if (k > 0 && n < e) {
n += pq.poll() * -1;
k--; // 무적권 사용횟수 차감
}
n -= e;
if (n < 0) {
break;
}
answer++;
}
return answer;
}
}
우선순위 큐를 활용하여 해결
내림차순을 이용하는 경우, Collections.reverseOrder()가 생각 안 날 때 -1을 곱해서 큐에 담은 뒤에 -1을 곱해서 꺼내기
🔑 다른 풀이
import java.util.*;
class Solution {
public int solution(int n, int k, int[] enemy) {
if(k == enemy.length) return k;
int ans = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int e : enemy){
if(k > 0){
k--;
pq.offer(e);
}else{
int num = pq.poll();
if(num < e){
pq.offer(e);
n-=num;
}else{
n-=e;
pq.offer(num);
}
if(n < 0) break;
}
ans++;
}
return ans;
}
}
'프로그래머스' 카테고리의 다른 글
[프로그래머스] 롤케이크 자르기 - LV2 (1) | 2025.02.14 |
---|---|
[프로그래머스] 오픈채팅방 - LV 2 (3) | 2025.02.12 |
[프로그래머스] 콜라 문제 (0) | 2024.09.30 |
[프로그래머스] 가장 가까운 같은 글자 (1) | 2024.09.25 |
[프로그래머스] 두 개 뽑아서 더하기 (0) | 2024.09.24 |
@킴준현 :: 차근차근 꾸준히
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!