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[1]));
PriorityQueue < int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[2]));
for (int[] trip : trips) {
while (!pq.isEmpty() && pq.peek()[2] <= trip[1]) {
capacity += pq.poll()[0];
}
if (capacity < trip[0]) {
return false;
}
pq.add(trip);
capacity -= trip[0];
}
return true;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#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 &
Try With Live Editor
Input
Output
#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)[1]
if cur > capacity: return False
return True
Copy The Code &
Try With Live Editor
Input
Output
#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[1001];
foreach (int[] trip in trips)
{
timestamp[trip[1]] += trip[0];
timestamp[trip[2]] -= trip[0];
}
int ued_capacity = 0;
foreach (int number in timestamp)
{
ued_capacity += number;
if (ued_capacity > capacity)
return false;
}
return true;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output