Eliminate Maximum Number of Monsters — LeetCode 1921 Python Solution
- Problem
- #1921
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are playing a video game where you are defending your city from a group of n monsters. 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.
Example
- Input
- dist = [1,3,4], speed = [1,1,1]
- Output
- 3
- Explanation
- In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
Python solution
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
times = sorted((d - 1) // s for d, s in zip(dist, speed))
for i, t in enumerate(times):
if t < i:
return i
return len(times)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1921. Eliminate Maximum Number of Monsters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1921. Eliminate Maximum Number of Monsters?
- LeetCode 1921. Eliminate Maximum Number of Monsters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1921. Eliminate Maximum Number of Monsters?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1921. Eliminate Maximum Number of Monsters?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1921. Eliminate Maximum Number of Monsters cover?
- LeetCode 1921. Eliminate Maximum Number of Monsters is tagged Greedy, Array and Sorting on LeetCode.