#
문제 설명
보유한 병사 n명으로 연속되는 적의
공격을 순서대로 최대 라운드까지 막는 게임
조건
매개 변수
n
k
enemy
반환값
n | k | enemy | result |
---|---|---|---|
7 | 3 | [4, 2, 4, 5, 3, 3, 1] | 5 |
2 | 4 | [3, 3, 3, 3] | 4 |
function solution(n, k, enemy) {
let result = 0;
const heap = new MaxHeap();
for (const e of enemy) {
heap.push(e);
n -= e;
if (n < 0) {
if (k <= 0) break;
n += heap.pop();
k--;
}
result++;
}
return result;
}
class MaxHeap {
constructor() {
this.heap = [];
}
size() {
return this.heap.length;
}
swap(i1, i2) {
[this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]];
}
push(v) {
this.heap.push(v);
let currentIndex = this.size() - 1;
let parentIndex = Math.floor((currentIndex - 1) / 2);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = Math.floor((currentIndex - 1) / 2);
}
}
pop() {
const heapSize = this.size();
if (heapSize === 0) return null;
if (heapSize === 1) return this.heap.pop();
const maxV = this.heap[0];
this.heap[0] = this.heap.pop();
let currentIndex = 0;
while (true) {
const leftIndex = currentIndex * 2 + 1;
const rightIndex = currentIndex * 2 + 2;
let largestIndex = currentIndex;
if (leftIndex < heapSize && this.heap[leftIndex] > this.heap[largestIndex]) {
largestIndex = leftIndex;
}
if (rightIndex < heapSize && this.heap[rightIndex] > this.heap[largestIndex]) {
largestIndex = rightIndex;
}
if (largestIndex === currentIndex) break;
this.swap(largestIndex, currentIndex);
currentIndex = largestIndex;
}
return maxV;
}
}
풀이
최대 힙을 통해 solution 구하기