# Program to check whether we can pick up and drop every passenger in given list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix called requested_trips where each row containing [start_x, end_x, num_passengers], and we also have a capacity value. Now each requested trip asks to pick up num_passengers passenger at start_x and drop them off at end_x. We also have a car with the capacity that is given, and start at position x = 0. We want to to pick up every passenger and can only move right side, we have to check whether we can pick up and drop off everyone.

So, if the input is like trips = [[1, 25, 2], [3, 4, 3],[5, 12, 3]] capacity = 6, then the output will be True

To solve this, we will follow these steps −

• events := a new list

• for each set (sx, ex, np) in trips, do

• insert pair (sx, np) at the end of events

• insert pair (ex, −np) at the end of events

• carrying := 0

• for each pair (loc, delta) in the list of events (in sorted order), do

• carrying := carrying + delta

• if carrying > capacity, then

• return False

• return True

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, trips, capacity):
events = []
for sx, ex, np in trips:
events.append((sx, np))
events.append((ex, -np))
carrying = 0
for loc, delta in sorted(events):
carrying += delta
if carrying > capacity:
return False
return True
ob = Solution()
trips = [
[1, 25, 2],
[3, 4, 3],
[5, 12, 3]
]
capacity = 6
print(ob.solve(trips, capacity))

## Input

trips = [
[1, 25, 2],
[3, 4, 3],
[5, 12, 3] ]
capacity = 6

## Output

True
Published on 21-Oct-2020 15:52:54
Advertisements