Advertisement
Iam_Sandeep

1094. Car Pooling

Jul 26th, 2022
1,082
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. '''
  2. There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
  3.  
  4. You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.
  5.  
  6. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.
  7. '''
  8. class Solution:
  9.     def carPooling(self, trips: List[List[int]], cap: int) -> bool:
  10.         t=[0]*1001
  11.         for p,s,e in trips:
  12.             t[s]+=p
  13.             t[e]-=p
  14.         cur=0
  15.         for i in range(1001):
  16.             cur=cur+t[i]
  17.             if cur>cap:
  18.                 return False
  19.         return True
  20. #standard method
  21. class Solution:
  22.     def carPooling(self, a: List[List[int]], cap: int) -> bool:
  23.         start,end=[],[]
  24.         n=len(a)
  25.         for p,s,e in a:
  26.             start.append((s,p))
  27.             end.append((e,p))
  28.         start.sort()
  29.         end.sort()
  30.         i,j=0,0
  31.         cur=0
  32.         while i<n and j<n:
  33.             if start[i][0]<end[j][0]:
  34.                 if cur+start[i][1]>cap:
  35.                     return False
  36.                 else:
  37.                     cur=cur+start[i][1]
  38.                     i+=1
  39.             else:
  40.                 cur=cur-end[j][1]
  41.                 j+=1
  42.         return True
  43.                
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement