class Solution {
public boolean carPooling(int[][] trips, int capacity) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int[] trip : trips) {
map.put(trip[1], map.getOrDefault(trip[1], 0) + trip[0]);
map.put(trip[2], map.getOrDefault(trip[2], 0) - trip[0]);
}
int max = 0;
int count = 0;
for (int value : map.values()) {
count += value;
max = Math.max(max, count);
if (max > capacity) {
return false;
}
}
return true;
}
}
/*
car goes with one direction
capacity
an array trips where trip[i] = [numPassengersi, fromi, toi]
from to pick and drop
in here the sweep line shows, it takes 2 + 3 = 5 people, 5 > 4, so it's fail
|
2 |
1. | 5
3.| 7
|3
when 3, pick up 3 more people, it's fail
2+3
*/
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
int[] bucket = new int[1001];
for (int i = 0; i < trips.length; i++) {
int[] trip = trips[i];
bucket[trip[1]] += trip[0];
bucket[trip[2]] -= trip[0];
}
int max = 0;
int count = 0;
for (int i = 0; i < bucket.length; i++) {
count += bucket[i];
max = Math.max(max, count);
if (max > capacity) {
return false;
}
}
return true;
}
}