-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1094_Car_Pooling.java
49 lines (37 loc) · 1.35 KB
/
1094_Car_Pooling.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
* 1094. Car Pooling
* Problem Link: https://leetcode.com/problems/car-pooling/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
Arrays.sort(trips, ( a, b) -> a[1] - b[1]);
int currentPassengerCount = 0;
int distance = 0;
// min heap (pair = to, numPassengers)
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[2] - b[2]);
// add capacity passengers.
for (int[] trip: trips) {
int numPassengers = trip[0];
// System.out.println("disctance is " + distance);
// we have travelled till start distance;
distance = trip[1];
while (!pq.isEmpty() && pq.peek()[2] <= distance){
// System.out.println("peek is " + Arrays.toString(pq.peek()));
currentPassengerCount -= pq.peek()[0];
pq.remove();
}
if ((numPassengers + currentPassengerCount) > capacity) {
return false;
}
pq.add( trip );
currentPassengerCount += numPassengers;
}
return true;
}
}