07. Eliminate Maximum Number of Monsters
The problem can be found at the following link: Question Link
My Approach
Initialize a vector of integers
timeto store the time it takes for each person to reach their destination.Inside the loop, calculate the time it takes for the current person to reach their destination:
Calculate the floating-point value by dividing
dist[i]byspeed[i].Use
ceilto round the floating-point result to the nearest integer.Store the rounded result in the
timevector.
After the loop, sort the
timevector in ascending order. This will give you a list of times in ascending order, representing when each person will reach their destination.Initialize an integer
tto 0. This variable will be used to keep track of the current time.Inside the loop, check if the current time
tis less than the timeifor the current person. If it is, incrementtby 1 to simulate the elimination of the person who arrives earliest.If the current time
tis greater than or equal to the timeifor the current person, break out of the loop since you have eliminated the maximum number of people possible without causing a collision.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(n)
Code (C++)
class Solution {
public:
int eliminateMaximum(vector<int>& dist, vector<int>& speed) {
vector<int> time;
for(int i=0;i<dist.size();i++){
int x = ceil((double)(dist[i])/(double)(speed[i]));
time.push_back(x);
}
sort(time.begin(),time.end());
int t =0;
for(auto i:time){
if(t<i) ++t;
else break;
}
return t;
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?