// Min priority queues for bus times and passenger Times.
priority_queue<int, vector<int>, greater<int>> busTimes{};
priority_queue<int, vector<int>, greater<int>> passengerTimes{};
int lastBus = -1;
for(const int& b : buses)
{
busTimes.push(b);
lastBus = std::max(lastBus, b);
}
for(const int& p : passengers)
{
passengerTimes.push(p);
}
// Keep track of the last processed passenger.
int lastPassenger = -1;
// The latest time that a user can catch a bus is -1, so far.
// If there are no more buses to catch, then use the latest time.
int latest = -1;
// topBus is the next bus. It has not been takin off the priority queue.
int topBus = busTimes.top();
// Current load is zero. Load can not exceed capacity.
int load = 0;
while(!busTimes.empty())
{
// If there are buses in the priority queue, but no more passengers, then catch the last bus.
if (passengerTimes.empty())
{
latest = lastBus;
break;
}
// Every time I pop a passenger, If the bus is full, then I pop the bus and
// reset the load to zero. At this point at the top of the while loop, there
// is room for at least one passenger on the top bus.
// topPassenger is the next passenger.
int topPassenger = passengerTimes.top();
// If topPassenger's time slot is less than or equal to topBus' time slot, then
// put passenger on the bus.
if ( topPassenger <= topBus)
{
// Before passenger is put on bus, note if the user can squeeze in before
// the topPassenger.
// If the time slot before topPassenger is empty,
// then latest time for user is updated to topPassenger - 1.
if (topPassenger - 1 > lastPassenger)
{
latest = topPassenger - 1;
}
// Pop the passenger, simulates the passenger getting on the bus.
passengerTimes.pop();
lastPassenger = topPassenger; // update the last passenger is topPassenger.
++load;
// If the top passenger is the last passenger on the bus because the
// bus is full or top passenger has the same time slot as the top bus,
// the pop the top bus.
if ( (capacity == load) || (topBus == topPassenger) )
{
busTimes.pop();
topBus = busTimes.top();
load = 0;
}
}
// Else topPassenger's time slot is larger than topBus's timeSlot.
else
{
// There is room for the user on topBus. The user should use the top bus'
// time slot.
latest = topBus;
// Pop the topBus and reset load.
busTimes.pop();
topBus = busTimes.top();
load = 0;
}
}
return latest;
}
};