You are a hero in a game, initially having HP health points and K magic potions.
You have to fight N monsters in the order they are given, knowing the damage each monster deals to you.
damage[i]
represents the damage the monster deals to you when you fight them. If the damage is negative, it means your HP increases by that amount.
If you use a magic potion on a monster, it will kill the monster without you fighting or losing health points.
If you reach zero HP, you die. Therefore you can't win agains a monster that has damage[i] >= HP
Find the maximum number of monsters you can kill, considering you are playing optimally.
Example
Input: K = 2, HP = 10,
damage = [-3, 2, 3, -2, 8, 8, 6, 4, 3, 3]
Output: 8
Explanation: You kill the first 8 monsters by using the two potions on the 6th and 7th monsters
The core challenge of this problem is to maximize the number of monsters you can kill while managing your health points (HP) and the limited number of magic potions (K). The damage array can have both positive and negative values, where positive values decrease your HP and negative values increase it. The key is to use the potions optimally to bypass the most damaging monsters.
To solve this problem, we need to consider the following steps:
Here is a step-by-step breakdown of the algorithm:
#include <iostream>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
int maxMonstersKilled(int K, int HP, vector<int>& damage) {
priority_queue<int> maxHeap;
int monstersKilled = 0;
for (int i = 0; i < damage.size(); ++i) {
if (damage[i] > 0) {
maxHeap.push(damage[i]);
}
HP -= damage[i];
monstersKilled++;
// If HP drops below zero, use a potion
if (HP < 0) {
if (K > 0 && !maxHeap.empty()) {
HP += maxHeap.top();
maxHeap.pop();
K--;
} else {
break;
}
}
}
return monstersKilled;
}
int main() {
int K = 2;
int HP = 10;
vector<int> damage = {-3, 2, 3, -2, 8, 8, 6, 4, 3, 3};
cout << "Maximum monsters killed: " << maxMonstersKilled(K, HP, damage) << endl;
return 0;
}
The time complexity of this approach is O(N log K), where N is the number of monsters and K is the number of potions. This is because we are using a max-heap to keep track of the most damaging monsters, and each insertion and deletion operation in the heap takes O(log K) time.
The space complexity is O(K) due to the storage required for the max-heap.
Consider the following edge cases:
To test the solution comprehensively, consider the following test cases:
When approaching such problems, consider the following tips:
In this blog post, we discussed how to solve the "Kill Monsters" problem using a max-heap to keep track of the most damaging monsters. We provided a detailed explanation of the algorithm, its implementation in C++, and analyzed its complexity. By understanding and practicing such problems, you can improve your problem-solving skills and prepare for coding interviews.
For further reading and practice, consider the following resources: