Problem Description
Given an initial planet mass and a list of asteroid masses, determine if all asteroids can be destroyed. The planet can destroy an asteroid if its mass is greater than or equal to the asteroid's mass, and upon doing so, the planet's mass increases by the mass of the asteroid. You are allowed to choose any order to collide with the asteroids.
Key Insights
- Sorting the asteroid array in increasing order maximizes the planet's mass gain early.
- By destroying the smallest asteroids first, the planet accumulates mass and is more likely to successfully destroy larger asteroids later on.
- The simulation terminates early if the planet cannot destroy a current asteroid.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the asteroids. Space Complexity: O(1) (ignoring the space taken by input data).
Solution
The approach is to sort the asteroids by their mass in ascending order. By doing so, we ensure that the smallest asteroids are destroyed first, which helps in increasing the planet's mass gradually. For each asteroid in the sorted list, we check if the planet's current mass is greater than or equal to the asteroid's mass:
- If it is, the asteroid is destroyed and its mass is added to the planet's mass.
- If it is not, then it becomes impossible to destroy this asteroid, so the function returns false. If the loop finishes successfully, then all asteroids have been destroyed and the function returns true.