Leetcode 1921: Eliminate Maximum Number of Monsters

grid47
grid47
Exploring patterns and algorithms
Apr 28, 2024 6 min read

You are defending your city from a group of n monsters. You are given two arrays dist and speed, where dist[i] is the initial distance of the ith monster from the city, and speed[i] is the speed of the ith monster in kilometers per minute. Your weapon takes one minute to charge and can eliminate one monster once fully charged. The game ends if any monster reaches the city before your weapon is ready. Return the maximum number of monsters you can eliminate or n if all monsters can be eliminated before they reach the city.
Problem
Approach
Steps
Complexity
Input: You are given two arrays dist and speed, both of size n. dist[i] is the initial distance of the ith monster, and speed[i] is the speed of the ith monster.
Example: dist = [2,4,6], speed = [2,1,1]
Constraints:
• 1 <= n <= 10^5
• 1 <= dist[i], speed[i] <= 10^5
Output: Return the maximum number of monsters that can be eliminated before any of them reach the city, or return n if all monsters can be eliminated.
Example: 3
Constraints:
Goal: Calculate the time each monster takes to reach the city, sort them, and eliminate monsters one by one until any of them reach the city.
Steps:
• For each monster, calculate the time it takes to reach the city: dist[i] / speed[i].
• Sort the times in ascending order.
• Iterate through the sorted times, and eliminate monsters as long as their arrival time is greater than the time elapsed (which increases with each elimination).
Goal: Ensure that the input follows the constraint limits for time and space efficiency.
Steps:
• n can go up to 10^5, so the solution needs to handle large inputs efficiently.
• Each dist[i] and speed[i] is guaranteed to be between 1 and 10^5.
Assumptions:
• The input arrays dist and speed will always have the same length.
• The values in dist are the initial distances of the monsters, and speed represents their constant speed.
Input: dist = [2,4,6], speed = [2,1,1]
Explanation: The monsters start at distances [2,4,6] and move at speeds [2,1,1]. We compute the time each monster takes to reach the city, which is [1,4,6]. After eliminating each monster one by one, we find that all 3 can be eliminated before reaching the city.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus