
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Car Pooling in Python
Suppose there is a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east, so we cannot turn around and drive west. We have given a list of trips, trip[i] = [num_passengers, start_location, end_location], that contains information about the ith trip:, so that is the number of passengers that must be picked up, and the locations to pick them up and drop them off. Here the locations are given as the number of kilometers due east from our vehicle's initial location. Our module will return true if and only if it is possible to pick up and drop off all passengers for all the given trips. So if trips are like [[2,1,5],[3,3,7]] and capacity is 5, then the output will be true.
To solve this, we will follow these steps −
- make one array called stops, of size 1000, and fill this with 0
- for i in trips
- stops[i[1]] := stops[i[1]] + i[0]
- stops[i[2]] := stops[i[1]] – i[0]
- for i in stops −
- capacity := capacity – i
- if capacity < 0, then return false
- return true when capacity >= 0
Let us see the following implementation to get better understanding −
Example
class Solution(object): def carPooling(self, trips, capacity): stops = [0 for i in range(1001)] for i in trips: stops[i[1]]+=i[0] stops[i[2]]-=i[0] for i in stops: capacity-=i if capacity<0: return False return capacity>=0 ob = Solution() print(ob.carPooling([[2,1,5],[3,3,7]],5))
Input
[[2,1,5],[3,3,7]] 5
Output
True