Problem
There are n
points on a road you are driving your taxi on. The n
points on the road are labeled from 1
to n
in the direction you are going, and you want to drive from point 1
to point n
to make money by picking up passengers. You cannot change the direction of the taxi.
The passengers are represented by a 0-indexed 2D integer array rides
, where rides[i] = [starti, endi, tipi]
denotes the ith
passenger requesting a ride from point starti
to point endi
who is willing to give a tipi
dollar tip.
For each passenger i
you pick up, you earn endi - starti + tipi
dollars. You may only drive at most one passenger at a time.
Given n
and rides
, return the maximum number of dollars you can earn by picking up the passengers optimally.
Note: You may drop off a passenger and pick up a different passenger at the same point.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Sorting + Binary Search
Here is the approach:
- Sort Rides:
- First, sort the rides based on their end points to facilitate processing in a single pass with dynamic programming.
- Dynamic Programming Array:
- Use a
dp
array wheredp[i]
represents the maximum earnings achievable by the time we reach pointi
.
- Use a
- Job Scheduling:
- For each ride, calculate the profit and use previously computed
dp
values to make decisions. - Update the
dp
array considering whether to take a new ride or not.
- For each ride, calculate the profit and use previously computed
- Binary Search:
- Use binary search to quickly find the rides that end before the start of a given ride.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k log k)
, wherek
is the number of rides.- Sorting the rides -
O(k log k)
- Filling the
dp
array:O(k log k)
due to the binary search.
- Sorting the rides -
- 🧺 Space complexity:
O(n + k)
, wheren
is the number of points andk
is the number of rides.