Minimum Average Waiting Time

  • + 0 comments

    I always prefer to give variables more meaningful names, and provide some comments. In my solution, currently_waiting is a heap of customers that already placed their orders, updated every loop.

    import heapq
    
    def minimumAverage(customers):
        # customers = [(order_time, cooking_time)]
        customers.sort()  # Sort by order time, then cooking time
        number_of_customers = len(customers)
        current_time = total_wait = 0
        currently_waiting = []
        while customers or currently_waiting:
            # Move to a heap of currently-waiting customers (as of `current_time`)
            while customers and customers[0][0] <= current_time:
                order_time, cooking_time = customers.pop(0)
                heapq.heappush(currently_waiting, (cooking_time, order_time))
            if not currently_waiting:
                # no orders yet, so fast forward to next customer
                current_time = customers[0][0]
                continue
            # Cook the order that will finish the sooner (first item on the heap)
            cooking_time, order_time = heapq.heappop(currently_waiting)
            total_wait += current_time + cooking_time - order_time
            current_time += cooking_time
        return total_wait // number_of_customers