Minimum Average Waiting Time

  • + 0 comments

    lol the answer is long long but the question use int, if you're getting errors change int to long long in return type and in the main function

    O(nlog n)

    struct Compare {
        bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
            if (a.second == b.second) {
                return a.first > b.first;
            }
            return a.second > b.second;
        }
    };
    
    long long minimumAverage(vector<vector<int>> customers) {
        sort(customers.begin(), customers.end());
        long long totalTime = 0;
        long long currentTime = 0;
        int pizzaCooked = 0;
        int i = 0;
        vector<pair<int, int>> pendingOrders;
        while (pizzaCooked != customers.size()) {
            while (i < customers.size() and customers[i][0] <= currentTime) {
                pendingOrders.push_back({customers[i][0], customers[i][1]});
                push_heap(pendingOrders.begin(), pendingOrders.end(), Compare());
                i++;
            }
            if (pendingOrders.empty()) currentTime = customers[i][0];
            else {
                currentTime = currentTime + pendingOrders[0].second;
                pizzaCooked++;
                totalTime = totalTime + currentTime - pendingOrders[0].first;
                pop_heap(pendingOrders.begin(), pendingOrders.end(), Compare());
                pendingOrders.pop_back();
            }
        }
        return totalTime/customers.size();
    }