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 trueif it is possible to pick up and drop off all passengers for all the given trips, orfalseotherwise.
The key idea is to track the net change in the number of passengers at each location using a difference array or map. For every trip, we increase the passenger count at the pickup point and decrease it at the drop-off point. By sweeping through the locations in order, we can efficiently check if the number of passengers ever exceeds the car’s capacity.
#include<map>usingnamespace std;
classSolution {
public:bool carPooling(vector<vector<int>>& trips, int cap) {
map<int, int> m;
for (auto& t : trips) {
m[t[1]] += t[0];
m[t[2]] -= t[0];
}
int cur =0;
for (auto& [_, v] : m) {
cur += v;
if (cur > cap) return false;
}
return true;
}
};
classSolution {
publicbooleancarPooling(int[][] trips, int cap) {
TreeMap<Integer, Integer> m =new TreeMap<>();
for (int[] t : trips) {
m.put(t[1], m.getOrDefault(t[1], 0) + t[0]);
m.put(t[2], m.getOrDefault(t[2], 0) - t[0]);
}
int cur = 0;
for (int v : m.values()) {
cur += v;
if (cur > cap) returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcarPooling(trips: Array<IntArray>, cap: Int): Boolean {
val m = sortedMapOf<Int, Int>()
for (t in trips) {
m[t[1]] = m.getOrDefault(t[1], 0) + t[0]
m[t[2]] = m.getOrDefault(t[2], 0) - t[0]
}
var cur = 0for (v in m.values) {
cur += v
if (cur > cap) returnfalse }
returntrue }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcarPooling(self, trips: list[list[int]], cap: int) -> bool:
m = {}
for num, start, end in trips:
m[start] = m.get(start, 0) + num
m[end] = m.get(end, 0) - num
cur =0for k in sorted(m):
cur += m[k]
if cur > cap:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::BTreeMap;
impl Solution {
pubfncar_pooling(trips: Vec<Vec<i32>>, cap: i32) -> bool {
letmut m = BTreeMap::new();
for t in&trips {
*m.entry(t[1]).or_insert(0) += t[0];
*m.entry(t[2]).or_insert(0) -= t[0];
}
letmut cur =0;
for v in m.values() {
cur += v;
if cur > cap { returnfalse; }
}
true }
}
We can efficiently track ongoing trips by sorting all trips by their start time and using a min-heap to keep track of the end times of current passengers. As we process each trip, we remove all trips from the heap that have already ended, freeing up capacity. This allows us to always know the current number of passengers in the car and check if adding a new trip would exceed the capacity.
Use a min-heap to keep track of ongoing trips, ordered by their end location.
Simulate the Process:
For each trip:
Remove all trips from the heap whose end location is less than or equal to the current trip’s start location, adding their passengers back to the available capacity.
Subtract the current trip’s passengers from the available capacity.
If capacity goes negative, return false.
Add the current trip to the heap.
Return Result:
If all trips are processed without exceeding capacity, return true.
classSolution {
publicbooleancarPooling(int[][] trips, int cap) {
Arrays.sort(trips, Comparator.comparingInt(t -> t[1]));
PriorityQueue<int[]> pq =new PriorityQueue<>(Comparator.comparingInt(t -> t[2]));
for (int[] t : trips) {
while (!pq.isEmpty() && t[1]>= pq.peek()[2]) {
cap += pq.poll()[0];
}
cap -= t[0];
if (cap < 0) returnfalse;
pq.offer(t);
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcarPooling(trips: Array<IntArray>, cap: Int): Boolean {
trips.sortBy { it[1] }
val pq = java.util.PriorityQueue<IntArray>(compareBy { it[2] })
var c = cap
for (t in trips) {
while (pq.isNotEmpty() && t[1] >= pq.peek()[2]) {
c += pq.poll()[0]
}
c -= t[0]
if (c < 0) returnfalse pq.add(t)
}
returntrue }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import heapq
classSolution:
defcarPooling(self, trips: list[list[int]], cap: int) -> bool:
trips.sort(key=lambda x: x[1])
h = []
for num, start, end in trips:
while h and start >= h[0][0]:
cap += heapq.heappop(h)[1]
cap -= num
if cap <0:
returnFalse heapq.heappush(h, (end, num))
returnTrue