#1921
Eliminate Maximum Number of Monsters
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages sorting and a greedy approach to ensure that we eliminate monsters in the order of their arrival times while keeping track of the time taken to eliminate each monster. This approach is efficient and avoids unnecessary calculations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the time for each monster to reach the city and store it in an array.
- 2Step 2: Sort the array of times.
- 3Step 3: Iterate through the sorted times, and for each monster, check if the current time (number of monsters eliminated) is less than the monster's arrival time. If true, eliminate the monster; otherwise, return the count.
solution.py6 lines
1def eliminateMaximum(dist, speed):
2 times = sorted(dist[i] / speed[i] for i in range(len(dist)))
3 for i in range(len(times)):
4 if i >= times[i]:
5 return i
6 return len(dist)ℹ
Complexity note: The optimal solution also has a time complexity of O(n log n) due to sorting, but it is more efficient in practice because it minimizes unnecessary checks and calculations.
- 1Monsters must be eliminated in the order of their arrival times to maximize the number eliminated.
- 2Sorting the arrival times allows for a simple linear pass to determine how many can be eliminated.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.