Problem Description
You are given two arrays, dist and speed, where dist[i] is the initial distance of the iᵗʰ monster from your city and speed[i] is its speed (in km/min). Your weapon is initially charged and can eliminate one monster per minute (after which it needs one minute to recharge). However, if a monster reaches your city (or arrives exactly when your weapon finishes recharging), you lose. The goal is to determine the maximum number of monsters you can eliminate before any one reaches the city, or eliminate all monsters if possible.
Key Insights
- Compute each monster's arrival time as dist[i] / speed[i].
- Sort the arrival times in ascending order.
- Use a greedy strategy: at minute i, eliminate the monster with the smallest arrival time.
- If the monster's arrival time is less than or equal to the current minute, then it reaches the city before you can eliminate it.
- Continue until you can no longer eliminate a monster before it arrives.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) to store the computed arrival times.
Solution
We first calculate the time each monster will reach the city by dividing its distance by its speed. We then sort these times. Starting from minute 0, we simulate the elimination of one monster per minute. If at the current minute the next monster's arrival time is less than or equal to the minute, it means that monster has reached the city, and the game is over. Otherwise, we successfully eliminate the monster and move to the next minute. The process continues until we either run out of monsters or encounter a monster whose arrival time is too soon.