Skip to content

Commit

Permalink
Create 1094_Car_Pooling.java
Browse files Browse the repository at this point in the history
  • Loading branch information
mkhuzaima committed Oct 12, 2023
1 parent 1bd779f commit 8b78a27
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions 1094_Car_Pooling.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// id: 1094
// Name: Car Pooling
// link: https://leetcode.com/problems/car-pooling/
// Difficulty: Medium

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;
}
}

0 comments on commit 8b78a27

Please sign in to comment.