Destroying Asteroids

medium array greedy sorting

Problem

A planet starts with a given mass and faces a list of asteroids, each with its own mass. The planet meets the asteroids one at a time, in any order you choose. When it meets an asteroid whose mass is less than or equal to the planet's current mass, the planet destroys it and gains that asteroid's mass; otherwise the planet itself is destroyed. Return true if there is an order in which the planet can destroy every asteroid, and false otherwise.

Inputmass = 10, asteroids = [3, 9, 19, 5, 21]
Outputtrue
Hit them smallest-first: 10→13→18→27→46→67. Every asteroid is no heavier than the planet at the moment of impact, so all are destroyed.

def asteroids_destroyed(mass, asteroids):
    asteroids.sort()
    total = mass
    for a in asteroids:
        if a > total:
            return False
        total += a
    return True
function asteroidsDestroyed(mass, asteroids) {
  asteroids.sort((a, b) => a - b);
  let total = mass;
  for (const a of asteroids) {
    if (a > total) return false;
    total += a;
  }
  return true;
}
class Solution {
    public boolean asteroidsDestroyed(int mass, int[] asteroids) {
        Arrays.sort(asteroids);
        long total = mass;
        for (int a : asteroids) {
            if (a > total) return false;
            total += a;
        }
        return true;
    }
}
bool asteroidsDestroyed(int mass, vector<int>& asteroids) {
    sort(asteroids.begin(), asteroids.end());
    long long total = mass;
    for (int a : asteroids) {
        if (a > total) return false;
        total += a;
    }
    return true;
}
Time: O(n log n) Space: O(1)