[LeetCode] Destroying Asteroids

2126. Destroying Asteroids

You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.

You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.

Return true if all asteroids can be destroyed. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool asteroidsDestroyed(long long mass, vector<int>& asteroids) {
sort(begin(asteroids), end(asteroids));
for(auto& a : asteroids) {
if(mass >= a) mass += a;
else return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/27/PS/LeetCode/destroying-asteroids/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.