#2126

Destroying Asteroids

specialist · 845 · lc medium +31 · verified · 53.4% accepted · 595 likes · top 44%

Description

You are given an integer mass representing the starting mass of a planet, and an integer array asteroids where asteroids[i] is the mass of the ith asteroid.

You can choose the order in which the planet encounters the asteroids. When the planet's mass is greater than or equal to an asteroid's mass, the asteroid is destroyed and its mass is added to the planet. If the asteroid is heavier, the planet is destroyed.

Return true if the planet can destroy all asteroids; otherwise return false.

Example 1:

Input: mass = 10, asteroids = [3,9,19,5,21]
Output: true
Explanation: One way to order the asteroids is [9,19,5,3,21]:
- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19
- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38
- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43
- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46
- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67
All asteroids are destroyed.

Example 2:

Input: mass = 5, asteroids = [4,9,23,4]
Output: false
Explanation:
The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.
After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.
This is less than 23, so a collision would not destroy the last asteroid.

Code

1
2
3