## Algorithm

Problem Name: 1094. Car Pooling

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`

## Code Examples

### #1 Code Example with Java Programming

```Code - Java Programming```

``````
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
Arrays.sort(trips, Comparator.comparingInt(o -> o));
PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a));
for (int[] trip : trips) {
while (!pq.isEmpty() && pq.peek() <= trip) {
capacity += pq.poll();
}
if (capacity < trip) {
return false;
}
capacity -= trip;
}
return true;
}
}
``````
Copy The Code &

Input

cmd
trips = [[2,1,5],[3,3,7]], capacity = 4

Output

cmd
false

### #2 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const carPooling = function(trips, capacity) {
const arr = Array(1001).fill(0)
for(const [num, s, e] of trips) {
arr[s] += num
arr[e] -= num
}
for(let i = 1; i < 1001; i++) {
arr[i] += arr[i - 1]
}

for(let e of arr) {
if(e > capacity) return false
}
return true
};
``````
Copy The Code &

Input

cmd
trips = [[2,1,5],[3,3,7]], capacity = 4

Output

cmd
false

### #3 Code Example with Python Programming

```Code - Python Programming```

``````
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
heap = []
for a, b, c in trips:
heapq.heappush(heap, (b, a))
heapq.heappush(heap, (c, -a))
cur = 0
while heap:
cur += heapq.heappop(heap)
if cur > capacity: return False
return True
``````
Copy The Code &

Input

cmd
trips = [[2,1,5],[3,3,7]], capacity = 5

Output

cmd
true

### #4 Code Example with C# Programming

```Code - C# Programming```

``````
namespace LeetCode
{
public class _1094_CarPooling
{
public bool CarPooling(int[][] trips, int capacity)
{
var timestamp = new int;

foreach (int[] trip in trips)
{
timestamp[trip] += trip;
timestamp[trip] -= trip;
}

int ued_capacity = 0;
foreach (int number in timestamp)
{
ued_capacity += number;
if (ued_capacity > capacity)
return false;
}
return true;
}
}
}
``````
Copy The Code &

Input

cmd
trips = [[2,1,5],[3,3,7]], capacity = 5

Output

cmd
true