Skip to content

Commit 01e785c

Browse files
authored
Create 1921-eliminate-maximum-number-of-monsters.cpp
1 parent 47f9ae2 commit 01e785c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: cpp/1921-eliminate-maximum-number-of-monsters.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
You are playing a video game where you are defending your city from a group of n monsters.
3+
You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.
4+
The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n,
5+
where speed[i] is the speed of the ith monster in kilometers per minute.
6+
You have a weapon that, once fully charged, can eliminate a single monster.
7+
However, the weapon takes one minute to charge.The weapon is fully charged at the very start.
8+
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged,
9+
it counts as a loss, and the game ends before you can use your weapon.
10+
11+
Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
12+
13+
Ex. Input: dist = [1,3,4], speed = [1,1,1]
14+
Output: 3
15+
Explanation:
16+
In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
17+
After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.
18+
After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.
19+
All 3 monsters can be eliminated.
20+
21+
Time : O(N)
22+
Space : O(N)
23+
*/
24+
25+
class Solution {
26+
public:
27+
int eliminateMaximum(vector<int>& dist, vector<int>& speed) {
28+
vector<float> v;
29+
30+
for(int i = 0 ; i < dist.size() ; i++)
31+
v.push_back((float) dist[i] / speed[i]);
32+
33+
sort(v.begin(), v.end());
34+
int count = 0;
35+
int time = 0, i = 0;
36+
while(i < v.size()) {
37+
if(time >= v[i])
38+
return count;
39+
++count;
40+
time += 1;
41+
++i;
42+
}
43+
return count;
44+
}
45+
};

0 commit comments

Comments
 (0)