Question
Formatted question description: https://leetcode.ca/all/1094.html
1094. Car Pooling
You are driving a vehicle that has capacity empty seats initially available for passengers.
The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip:
the number of passengers that must be picked up, and the locations to pick them up and drop them off.
The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
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
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Algorithm
For each interval, at start, there are passangers getting on, at end, there are passagers getting off.
Then arrange original interval as start with positive integer of passager count, end with negative integer of passage count.
Sort them based on time. Let negative number come first as they get off, could minimize current passager count.
If current passage count > capacity, return false.
Time Complexity: O(nlogn). n = trips.length.
Space: O(n).
Code
Java
public class Car_Pooling {
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
if(trips == null || trips.length == 0){
return true;
}
List<int []> list = new ArrayList<>();
for(int [] trip : trips){
list.add(new int[]{trip[1], trip[0]});
list.add(new int[]{trip[2], -trip[0]});
}
// same location, off bus first, then onboard new.
// so, negative value first, then positive value
Collections.sort(list, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
int count = 0;
for(int [] arr : list){
count += arr[1];
if(count > capacity){
return false;
}
}
return true;
}
}
}
Java
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
PriorityQueue<int[]> priorityQueue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] array1, int[] array2) {
if (array1[0] != array2[0])
return array1[0] - array2[0];
else
return array1[1] - array2[1];
}
});
for (int[] trip : trips) {
int passengersCount = trip[0], start = trip[1], end = trip[2];
int[] passengersStart = {start, passengersCount};
int[] passengersEnd = {end, -passengersCount};
priorityQueue.offer(passengersStart);
priorityQueue.offer(passengersEnd);
}
int passengers = 0;
while (!priorityQueue.isEmpty()) {
int[] passengersChange = priorityQueue.poll();
passengers += passengersChange[1];
if (passengers > capacity)
return false;
}
return true;
}
}