Before attempting this problem, you should be comfortable with:
We simulate the chef serving customers one by one. The chef can only start a new order when they finish the previous one. If a customer arrives while the chef is busy, they wait. The waiting time for each customer is the time from arrival until their order is complete. We track the current time and accumulate total waiting time.
t (current time) and total (total waiting time) to 0.t > arrival), add the extra wait to total.t to the arrival time.total and t.total divided by the number of customers.This is a more concise version of the simulation. The key observation is that the chef starts cooking at whichever is later: their current finish time or the customer's arrival. The finish time becomes max(t, arrival) + order. The customer's waiting time is simply finish_time - arrival. This formula captures both cases (chef idle or busy) in one expression.
t (finish time) and total to 0.t to max(t, arrival) + order (when the order finishes).t - arrival to total (customer's wait time).total divided by the number of customers.With large arrival times and order durations, the sum of waiting times can exceed 32-bit integer limits. Use 64-bit integers for accumulating totals.
// Wrong: int can overflow
int total = 0;
// Right: use long for accumulation
long total = 0;Waiting time is from arrival until the order is complete (includes cooking time), not just the time spent waiting before cooking starts.
# Wrong: only counting idle wait time
wait = max(0, t - arrival)
# Right: total time from arrival to completion
wait = (max(t, arrival) + order) - arrivalWhen a customer arrives after the chef is idle, the current time must jump forward to the arrival time, not stay at the previous finish time.
# Wrong: always adding order time to current t
t += order
# Right: chef starts at max(t, arrival)
t = max(t, arrival) + order