1094. Car Pooling

Problem Statement

There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).

You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.

Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.

Example 1:

Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:

Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true

Constraints:

  • 1 <= trips.length <= 1000

  • trips[i].length == 3

  • 1 <= numPassengersi <= 100

  • 0 <= fromi < toi <= 1000

  • 1 <= capacity <= 105

Intuition

Approach:

We insert the passengers during in time
and also in heap we push -pass, for exit time

At any moment, the capacity exceeds we return false

https://leetcode.com/problems/car-pooling/description/

Approach 1:

C++
class Solution {
public:
    bool carPooling(vector<vector<int>>& trips, int capacity) {
        //min priority_queue declare
        priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq; 
		
        for(int i=0;i<trips.size();i++){
		    // at arrival +x passanger start travelling so we add it.
            pq.push({trips[i][1],trips[i][0]});
			// at reaching destination -x passenger remove so we subtract it.
            pq.push({trips[i][2],-trips[i][0]});
        }
		//intailly no passnger present  so check=0
        int check=0;
		
        while(!pq.empty()){
		   //add passanger from minp_q
            check+=pq.top().second;
            pq.pop();
			//if  check >capacity then it is impossible to travel 
            if(check>capacity)
                return false;
        }
        return true;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated