Minimum Average Waiting Time

  • + 0 comments

    Python3 solution with explanation!

    def minimumAverage(customers):
        # Customers is a list of tuples. I assume it's already
        # sorted by i[0], the arrival time, but let's make sure.
        # We'll also need to know the total customer number in
        # order to calculate the average wait later on.
        
        customers.sort()
        cust_count = len(customers)
        
        # Since the minimum average wait will always be reached
        # by preparing the quickest pizza first, we want to store
        # the pizzas in a min heap sorted by required cook time.
        
        # As we start cooking, we'll pull customers off the list
        # and put them into a heap of waiting customers. We'll
        # also need to track time throughout the process to know
        # when to add to the heap or remove from it. And since
        # we're calculating average using the total number of
        # customers, we need a variable for total wait time to
        # divide by it.
        
        waiting = []
        time = 0
        wait_time = 0
        
        # This whole process will run until there are no more
        # customers in either list.
        
        while customers or waiting:
            
            # Move customers to waiting once they've ordered.
            # Flip tuple values for correct priority sort.
            while customers and time >= customers[0][0]:
                t_order, t_cook = customers.pop(0)
                heapq.heappush(waiting, (t_cook, t_order))
            
            # If we're waiting for orders, jump to the next.
            if len(waiting) == 0:
                time = customers[0][0]
                continue
            
            # We don't want to move one second at a time as
            # that would confuse priority. We want to think
            # of time in the form of pizzas cooked. So,
            # instead of incrementing time, we'll add the
            # cook time of the highest priority pizza, one at
            # a time. That will give the time the customer is
            # served, from which we subtract their order time
            # to know their wait and add it to the total wait.
            
            cook, order = heapq.heappop(waiting)
            time += cook
            wait_time += (time - order)
            
        # Use // to return only the integer part of avg time.
        return wait_time // cust_count