LCP 30. 魔塔游戏

LCP 30. 魔塔游戏

解法一: 贪心

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int magicTower(int[] nums) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((num1, num2) -> num1 - num2);
int ans = 0;
long hp = 1;
long last = 0;
for (int num : nums) {
hp += num;
if (num < 0) {
priorityQueue.offer(num);
if (hp <= 0) {
Integer moveNum = priorityQueue.poll();
last += moveNum;
hp -= moveNum;
ans++;
}
}
}
hp += last;
return hp <= 0 ? -1 : ans;
}
}
作者

wuhunyu

发布于

2024-02-06

更新于

2024-02-06

许可协议