{x}
blog image

Maximum Earnings From Taxi

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.

 

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 <= 105
  • 1 <= rides.length <= 3 * 104
  • rides[i].length == 3
  • 1 <= starti < endi <= n
  • 1 <= tipi <= 105

Solution Explanation: Maximum Earnings From Taxi

This problem asks to find the maximum earnings from taxi rides, given a set of rides with start points, end points, and tips. The key constraint is that you can only drive one passenger at a time, and you must proceed in the direction from point 1 to point n.

We can solve this problem efficiently using dynamic programming or memoization with binary search. Both approaches have a time complexity of O(m log m), where m is the number of rides. The space complexity is O(m) for both.

  1. Sort Rides: First, sort the rides array by start point (start_i). This helps in efficiently finding the next available ride after completing a current ride.

  2. Recursive DFS (with Memoization): A recursive function dfs(i) calculates the maximum earnings starting from the i-th ride.

    • Base Case: If i is beyond the number of rides, the earnings are 0.
    • Recursive Step: For each ride i, we have two choices:
      • Skip the ride: The maximum earnings are dfs(i + 1).
      • Take the ride: The earnings are end_i - start_i + tip_i. To find the next available ride, we perform a binary search on the sorted rides array to find the index j of the first ride whose start_j is greater than or equal to end_i. The total earnings in this case become dfs(j) + end_i - start_i + tip_i.
    • Memoization: We use a cache (e.g., @cache in Python) to store the results of dfs(i) to avoid redundant calculations.
  3. Initial Call: The maximum earnings are obtained by calling dfs(0).

This approach is very similar to memoization but eliminates recursion by using an array to store the results.

  1. Sort Rides: Sort the rides array by end point (end_i). This order ensures that when we consider a ride, we've already processed all rides that could precede it.

  2. DP Array: Create a DP array f of size m + 1, where f[i] represents the maximum earnings up to the i-th ride (inclusive). f[0] is initialized to 0.

  3. Iteration: Iterate through the rides. For each ride i:

    • f[i] is the maximum of:
      • f[i - 1] (skip the current ride).
      • f[j] + end_i - start_i + tip_i (take the current ride, where j is the index of the last ride whose end_j is less than or equal to start_i. This is found using binary search).
  4. Result: f[m] contains the maximum earnings from all rides.

Time and Space Complexity

Both approaches have the same complexity:

  • Time Complexity: O(m log m) due to the sorting step and the m binary searches (each taking O(log m) time).
  • Space Complexity: O(m) for the DP array or memoization cache.

Code Examples (Python)

Approach 1 (Memoization):

from functools import cache
import bisect
 
class Solution:
    def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
        rides.sort()  # Sort by start point
 
        @cache
        def dfs(i: int) -> int:
            if i >= len(rides):
                return 0
            st, ed, tip = rides[i]
            j = bisect_left(rides, ed, lo=i + 1, key=lambda x: x[0])
            return max(dfs(i + 1), dfs(j) + ed - st + tip)
 
        return dfs(0)

Approach 2 (Dynamic Programming):

import bisect
 
class Solution:
    def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
        rides.sort(key=lambda x: x[1])  # Sort by end point
        m = len(rides)
        f = [0] * (m + 1)
        for i, (st, ed, tip) in enumerate(rides, 1):
            j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1])  # Binary search for previous ride
            f[i] = max(f[i - 1], f[j] + ed - st + tip)
        return f[m]

These examples demonstrate both approaches. The other languages (Java, C++, Go, TypeScript) would follow similar logic, adapting the specific syntax and data structures of each language. Remember that the binary search implementation might slightly vary depending on the language's standard library.