Average Waiting time (Simulation based question)
Problem link
Approach
Initially, when the chef is not doing anything and a customer arrives, the waiting time for the customer to get a particular dish ordered is nothing but just the preparation time.
Now, let's suppose the chef is preparing the food and meanwhile another customer arrives. In that case, the waiting time would be the last preparation time plus the new preparation time minus the time when the customer arrived.
Another possible case is that the chef has prepared and delivered the dish and is now not doing anything. In that case, we need to deal with this customer as we did in step 1.
We will add up the waiting time and divide by the number of customers which is give by
customers.size();
.
Code
class Solution {
public:
double averageWaitingTime(vector<vector<int>>& customers) {
int n = customers.size();
double prep = customers[0][0]+customers[0][1];
double w = prep - customers[0][0];
for(int i = 1;i<n;i++){
if(prep>customers[i][0]){
prep = prep + customers[i][1];
w = w + (prep - customers[i][0]);
}
else{
prep = customers[i][0]+customers[i][1];
w = w + (prep - customers[i][0]);
}
}
return w/n;
}
};
Let me know your doubts in the comment section.
All the best for your DSA journey! Let me know your feedback so that we can improve this article together.
Ujjwal Sharma
Subscribe to my newsletter
Read articles from Ujjwal Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by