Maximum Earnings From Taxi — LeetCode 2008 Python Solution

MediumArrayHash TableBinary SearchDynamic ProgrammingSorting
Problem
#2008
Reading time
2 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
        @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)

        rides.sort()
        return dfs(0)

Complexity

MeasureComplexity
TimeO(m \times \log m)
SpaceO(m) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 2008. Maximum Earnings From Taxi is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2008. Maximum Earnings From Taxi?
LeetCode 2008. Maximum Earnings From Taxi is rated Medium on LeetCode.
What is the time complexity of LeetCode 2008. Maximum Earnings From Taxi?
The Python solution on this page runs in O(m \times \log m).
What is the space complexity of LeetCode 2008. Maximum Earnings From Taxi?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 2008. Maximum Earnings From Taxi cover?
LeetCode 2008. Maximum Earnings From Taxi is tagged Array, Hash Table, Binary Search, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview