Maximum Earnings From Taxi Problem
Description
LeetCode Problem 2008.
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] = [start_i, end_i, tip_i] denotes the i^th passenger requesting a ride from point start_i to point end_i who is willing to give a tip_i dollar tip.
For each passenger i you pick up, you earn end_i - start_i + tip_i 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.
Example 1:
Input: n = 5, rides = [[2,5,4],[1,5,1]]
Output: 7
Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.
Example 2:
Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]
Output: 20
Explanation: We will pick up the following passengers:
- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.
- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.
- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.
We earn 9 + 5 + 6 = 20 dollars in total.
Constraints:
1 <= n <= 10^51 <= rides.length <= 3 * 10^4rides[i].length == 31 <= start_i < end_i <= n1 <= tip_i <= 10^5
Solution
Approach: Dynamic Programming Over Positions
Let f[i] be the best total earnings if the taxi is at position i and may still use any ride that starts at i or later. Then f[n] is 0, and for each i from n - 1 down to 1 there are two options: skip the point and get f[i + 1], or take a ride [i, end, tip] that starts here and earn end - i + tip plus f[end]. So
f[i] = max(f[i + 1], max over rides starting at i of (f[end] + end - i + tip))
Group the rides by start point first, so every ride is looked at once. The answer is f[1]. Sums can exceed 32 bits (up to about 6 * 109), so use 64-bit integers.
Complexity: O(n + m) time and O(n + m) space, where m is the number of rides.
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
starts = [[] for _ in range(n + 1)]
for st, ed, tip in rides:
starts[st].append((ed, ed - st + tip))
f = [0] * (n + 2)
for i in range(n - 1, 0, -1):
f[i] = f[i + 1]
for ed, gain in starts[i]:
f[i] = max(f[i], f[ed] + gain)
return f[1]