Advertisement
jorupp

https://leetcode.com/problems/car-fleet/

Sep 25th, 2023
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. function carFleet(target: number, position: number[], speed: number[]): number {
  2. // we don't have to acutally simulate the whole trip
  3. // 1. figure out when each car would arrive at the destination if it were the only car
  4. // 2. find the number of cars that had no cars that started ahead of it arrive at or after it would have
  5.  
  6. // a. create an array of arrival times ordered by start position, starting with the highstart starting position
  7. // b. every time you see a new highest arrival time, increment counter
  8.  
  9. const carState = position.map((i, ix) => ({ start: i, arrival: (target-i)/speed[ix] })).sort((a,b) => b.start - a.start);
  10.  
  11. let worst = 0;
  12. let count = 0;
  13. for(const { arrival } of carState) {
  14. if (arrival > worst) {
  15. worst = arrival;
  16. count++;
  17. }
  18. }
  19. return count;
  20. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement