Skip to content

2126. Destroying Asteroids

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  bool asteroidsDestroyed(int mass, vector<int>& asteroids) {
    ranges::sort(asteroids);

    long m = mass;

    for (const int asteroid : asteroids)
      if (m >= asteroid)
        m += asteroid;
      else
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean asteroidsDestroyed(int mass, int[] asteroids) {
    Arrays.sort(asteroids);

    long m = mass;

    for (final int asteroid : asteroids)
      if (m >= asteroid)
        m += asteroid;
      else
        return false;

    return true;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def asteroidsDestroyed(self, mass: int, asteroids: list[int]) -> bool:
    for asteroid in sorted(asteroids):
      if mass >= asteroid:
        mass += asteroid
      else:
        return False
    return True